Javascript遍历JSON仅获得第一个元素? [英] Javascript each loop over JSON only getting first element?

查看:87
本文介绍了Javascript遍历JSON仅获得第一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Jquery mobile,因此请忽略以下一些过高的CSS,它与核心问题无关.

I'm using Jquery mobile, so ignore some of the following overdone css, its not related to the core issue.

我在遍历JSON数据包/javascript对象中的位置"时遇到问题.我收到了多个地方"的回复,但似乎无法弄清楚如何对其进行迭代.我的每个循环中的"i"变量对于第一个元素均正常工作,并显示其对应的名称&图片.

I'm having a problem looping over the "Places" in my JSON packet/javascript object. I am getting a response with multiple "Places", but can't seem to figure out how to iterate over them. My 'i' variable in my each loop is working correctly for the first element, and displaying its corresponding name & image.

这是我的服务器端Django视图(如果您不熟悉Python,则非常简单):

Here's my server side Django view (pretty straight-forward if your unfamiliar with Python):

def tonight_mobile(request):

    callback = request.GET.get('callback', '')

    def with_rank(rank, place):
        return (rank > 0)

    place_data = dict(
        Places = [make_mobile_place_dict(request, p) for p in Place.objects.all()]
    )

    xml_bytes = json.dumps(place_data)
    return HttpResponse(xml_bytes, content_type='application/json; charset=utf-8')

我的服务器正在确认请求并返回以下内容:

My server is acknowledging the request and returning the following:

"GET /api/0.1/tonight-mobile.json&callback=jsonp1293142434434 HTTP/1.1" 200 167

这是我的回复:

callback({"Places": [{"url": "http://localhost:8000/api/0.1/places/3.plist", 
"image_url": "http://localhost:8000/static/place_logos/Bengals_1.png", 
"name": "Bob's Place", "events": 2}, 
{"url": "http://localhost:8000/api/0.1/places/2.plist", 
"image_url": "http://localhost:8000/static/place_logos/Makonde_Mask.gif", 
"name": "My Bar", "events": 0}, 
{"url": "http://localhost:8000/api/0.1/places/1.plist", 
"image_url": "http://localhost:8000/static/place_logos/Quintons_1.png", 
"name": "Quinton's", "events": 1}]})

------------

我的getJSON和回调方法已演变为:

------------

My getJSON and callback method have evolved into this:

<script>
function loadJSON(){
    $.getJSON("http://localhost:8000/api/0.1/tonight-mobile.json&callback=?", callback(data));
}
function callback(data){
    $("#tonight-list").each(data.Places, function(i) {
        $(this).append("<li role='option' tabindex='" + data.Places[i] + "' class='ui-li-has-thumb ui-li ui-btn ui-btn-icon-right ui-corner-top ui-corner-bottom ui-controlgroup-last ui-btn-down-c ui-btn-up-c' data-theme='c'><div class='ui-btn-inner ui-corner-top ui-corner-bottom ui-controlgroup-last'><span class='ui-icon ui-icon-arrow-r'></span><div class='ui-btn-text'><img src=" + data.Places[i].image_url + " alt=" + data.Places[i].name + " class='ui-li-thumb ui-corner-tl ui-corner-bl'/><h1 class='list-title ui-li-heading' id='list-title'><a href='detail.html?id=slide' data-transition='slide' class='ui-link-inherit'>" + data.Places[i].name + "</a></h1><span class='ui-li-count ui-btn-up-c ui-btn-corner-all'>" + data.Places[i].events + " events</span></div></div></li>");
    });

}
</script>

我感到困惑的是,每个函数如何遍历JSON(成为Javascript对象)?我很确定每个问题都是我的问题,因为我仅获得地方"列表中的第一个元素.有人可以帮我解决循环结构的问题吗?

Am I confusing how the each function iterates over the JSON (which become) Javascript objects? I am pretty sure the each is my issue here, as I am only getting the FIRST element of the "Places" list. Can someone please help me out as to how to structure the looping?

推荐答案

each()不能那样工作.它在页面上采用一组元素,并在它们上循环,为每个元素调用一个函数.在这种情况下,您要遍历$("#tonight-list"),它只会包含一个项目(ID应该唯一地标识文档中的一个元素).

each() doesn't work that way. It takes a set of elements on the page, and loops over them, calling a function for each one. In this case, you are looping over $("#tonight-list"), which will only have one item in it (IDs are supposed to uniquely identify one element in a document).

您似乎想要做的是遍历 data (不是#tonight-list元素),然后将数据添加到该元素,对吧?在这种情况下,您希望普通的JavaScript进行循环,如下所示:

What you seem to want to do is to loop over the data (not the #tonight-list element), and add the data to that element, right? In that case, you want normal JavaScript to do the loop, something like this:

var list = $("#tonight-list");
for (var i=0, place; place=data.Places[i]; ++i) {
    list.append("<li role='option' tabindex='" + i + "'>" + place.name + "</li> ...etc);
}

请注意,如果要加载包含HTML,不可信纯文本等内容的受信任数据,我不知道.您可能需要先对数据进行编码,然后再进行插入或(更好地)结构性插入而不是串联字符串,取决于您的用例.

Note that I have no idea if you are loading trusted data that is meant to contain HTML, untrusted plain text, etc. You may need to encode the data before inserting it or (better) insert it structurally instead of concatenating strings, depending on your use-case.

这篇关于Javascript遍历JSON仅获得第一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆