使用 Django 回调的 Javascript getJSON 问题

发布于 2024-10-08 20:44:49 字数 4940 浏览 8 评论 0原文

我正在尝试使用此脚本拨打电话,但收到“Uncaught SyntaxError: Unexpected token :

我不知道哪里出了问题,我不知道是否是这样与我的回调有关的东西。我正在发送一个有效的 JSON 数据包,所以我认为这不是问题所在。不管怎样,这是我的 html/jquery 调用:

<script>
function loadJSON(){
    $.getJSON("http://localhost:8000/api/0.1/tonight-mobile.json&callback=?", function(data){
            alert('hey');
             $('result').append(data);
             alert('hey 2'); 
         $.each(data, function(i, json){});

    });
    alert('hey 3');
}
</script>

在我的 django 视图中使用这个相应的函数:

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')

这是我的服务器记录的请求(所以我知道它至少能通过 OK 状态代码达到那么远):

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

在我的 javascript 中显示此错误控制台:

Uncaught SyntaxError: Unexpected token : tonight-mobile.json&callback=jsonp1293142434434:1

如果您需要查看我的 JSON 格式(如果这就是导致此问题的原因),请告诉我,我也可以发布它。

预先感谢您的帮助!


更新:

这是来自我的服务器的响应:

{"Places": [{"url": "http://localhost:8000/api/0.1/places/1.plist", "image_url": "http://localhost:8000/static/place_logos/Tsonoqua_Mask.gif", "name": "Boo's Place"}]}
[23/Dec/2010 17:37:22] "GET /api/0.1/tonight-mobile.json&callback=jsonp1293147441552 HTTP/1.1" 200 167

更新2:

我已经设法让我的回调正常工作!这是代码:

客户端:

<script>
function loadJSON(){
    $.getJSON("http://localhost:8000/api/0.1/tonight-mobile.json&callback=?", logIt(data));
}
function logIt(data){
    window.console && console.log(data);
    alert('yay!');
}
</script>

服务器端:

def tonight_mobile(request):
    callback = request.GET.get('callback', 'logIt')

    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)

    if callback:
        xml_bytes = '%s(%s)' % (callback, xml_bytes)
    print xml_bytes

    return HttpResponse(xml_bytes, content_type='application/javascript; charset=utf-8')

这将返回以下响应:

logIt({"Places": [{"url": "http://localhost:8000/api/0.1/places/1.plist", "image_url": "http://localhost:8000/static/place_logos/Tsonoqua_Mask.gif", "name": "Boo's Place"}]})

这是它应该如何运行的吗?看来我应该能够简化 getJSON 调用...我只是想确保在继续向前解析响应并将它们设置为页面上的元素之前,我已经通过回调正确完成了所需的所有操作。


更新3*

所以,我已经取得了相当大的进步!我使用的是 Jquery mobile,因此请忽略以下一些过度的 css,它与核心问题无关。

我在循环 JSON 数据包中的“地点”时遇到问题。我收到多个“地点”的响应,但似乎不知道如何迭代它们。我的每个循环中的“i”变量对于第一个元素正常工作,并显示其相应的名称和名称。 我是否

我的 getJSON 和回调方法已经演变成这样:

<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>

这是我的回应:

callback({"Places": [{"url": "http://localhost:8000/api/0.1/places/3.plist", "image_url": "http://localhost:8000/static/place_logos/Bengals_1.png", "name": "Big 12", "events": 2}, {"url": "http://localhost:8000/api/0.1/places/2.plist", "image_url": "http://localhost:8000/static/place_logos/Makonde_Mask.gif", "name": "Harpo's", "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}]})

对每个函数如何迭代 JSON(变成)Javascript 对象感到困惑?我很确定每个都是我的问题,因为我只得到“地点”列表的第一个元素。有人可以帮我吗?

I am trying to make a call with this script, but am getting a "Uncaught SyntaxError: Unexpected token :"

I can't figure out where I'm going wrong, I don't know if it's something with my callback. I am sending a valid JSON packet so I don't think that's the issue. Anyway, here's my html/jquery call:

<script>
function loadJSON(){
    $.getJSON("http://localhost:8000/api/0.1/tonight-mobile.json&callback=?", function(data){
            alert('hey');
             $('result').append(data);
             alert('hey 2'); 
         $.each(data, function(i, json){});

    });
    alert('hey 3');
}
</script>

With this corresponding function in my django view:

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')

Here is my request being logged by my server (so I know its at least getting that far with a OK status code):

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

Displaying this error in my javascript console:

Uncaught SyntaxError: Unexpected token : tonight-mobile.json&callback=jsonp1293142434434:1

If you need to see my JSON format (if that is what's causing this) please let me know and I can post it too.

Thank you in advance for your help!


UPDATE:

Here's the response coming from my server:

{"Places": [{"url": "http://localhost:8000/api/0.1/places/1.plist", "image_url": "http://localhost:8000/static/place_logos/Tsonoqua_Mask.gif", "name": "Boo's Place"}]}
[23/Dec/2010 17:37:22] "GET /api/0.1/tonight-mobile.json&callback=jsonp1293147441552 HTTP/1.1" 200 167

UPDATE 2:

I've managed to get my callback working correctly! Here's the code:

Client side:

<script>
function loadJSON(){
    $.getJSON("http://localhost:8000/api/0.1/tonight-mobile.json&callback=?", logIt(data));
}
function logIt(data){
    window.console && console.log(data);
    alert('yay!');
}
</script>

Server side:

def tonight_mobile(request):
    callback = request.GET.get('callback', 'logIt')

    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)

    if callback:
        xml_bytes = '%s(%s)' % (callback, xml_bytes)
    print xml_bytes

    return HttpResponse(xml_bytes, content_type='application/javascript; charset=utf-8')

This returns the following response:

logIt({"Places": [{"url": "http://localhost:8000/api/0.1/places/1.plist", "image_url": "http://localhost:8000/static/place_logos/Tsonoqua_Mask.gif", "name": "Boo's Place"}]})

Is this how it should function? It seems I should be able to simplify the getJSON call... I just want to make sure I've done everything I need to correctly with my callback before I continue forward parsing the response and setting them to elements on the page.


UPDATE 3*

So, I've made quite some progress!! I'm using Jquery mobile, so ignore some of the following overdone css, its not related to the core issue.

I'm having a problem looping over the "Places" in my JSON packet. 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.

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>

Here's my response:

callback({"Places": [{"url": "http://localhost:8000/api/0.1/places/3.plist", "image_url": "http://localhost:8000/static/place_logos/Bengals_1.png", "name": "Big 12", "events": 2}, {"url": "http://localhost:8000/api/0.1/places/2.plist", "image_url": "http://localhost:8000/static/place_logos/Makonde_Mask.gif", "name": "Harpo's", "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}]})

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

爱冒险 2024-10-15 20:44:49

是的,要返回 jsonp,您需要将响应包装在函数中:

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)
    if callback:
        xml_bytes = '%s(%s)' % (callback, xml_bytes)
    return HttpResponse(xml_bytes, content_type='application/json; charset=utf-8')

Yes to return jsonp you need to wrap the response in a function:

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)
    if callback:
        xml_bytes = '%s(%s)' % (callback, xml_bytes)
    return HttpResponse(xml_bytes, content_type='application/json; charset=utf-8')
凉墨 2024-10-15 20:44:49

看起来不错,您可以像这样简化 getJSON 调用:

function loadJSON(){
    var url = "http://localhost:8000/api/0.1/tonight-mobile.json&callback=?";
    $.getJSON(url, function(data){
        if(data){
            console.log(data.name);
        }
    });
}

在您的 python 代码中,如果未提供回调,我会这样做

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

,而不是

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

返回 json 而不是 jsonp。

That looks good, you could simplify the getJSON call like this:

function loadJSON(){
    var url = "http://localhost:8000/api/0.1/tonight-mobile.json&callback=?";
    $.getJSON(url, function(data){
        if(data){
            console.log(data.name);
        }
    });
}

In your python code I would do

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

instead of

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

so if callback is not provided json will be returned instead of jsonp.

眼前雾蒙蒙 2024-10-15 20:44:49

您正在混合 JSON 和 JSONP。当 jQuery 期望使用回调参数包装 JSON 对象时,您的 Django 脚本返回 JSON 对象:

callback(JSON string);

You're mixing JSON and JSONP. Your Django script is returning a JSON object, when jQuery is expecting a JSON object wrapped with the callback argument:

callback(JSON string);

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文