0

我已经搜索了这个站点和其他地方,试图解决我在使用 jsonp 时遇到的问题。首先,这是我拥有的代码:

url =  "http://mydomain.com/return_json";

$.ajax({
    url: url, // + '?callback=?' --I realized this is not necessary with dataType: 'jsonp'
    dataType: 'jsonp',
    crossDomain: true,
    error: function(xhr, status, error) {
            console.log(xhr);
            console.log(status);
            console.log(error);
        },
    success: function(dataWeGotViaJsonp){
        var text = '';
        var len = dataWeGotViaJsonp.length;
        for(var i=0;i<len;i++){
            item = dataWeGotViaJsonp[i];
            text += '<p>' + item + '</p>';
        }
        $('#action_target').html(text);
    }
});

在发送端,/return_jsonurl 是一个 Django 站点,它通过以下方式发送 json 数据:

def return_json(request):

    data = [{'testing': 'testing'}, {'one': 1, 'two': 2, 'three': 3}]

    return HttpResponse( json.dumps(data), content_type="application/javascript" )

正如您在 JavaScript 中看到的那样,我在出错时不加选择地将所有内容转储到控制台中。这是它的输出:

Object { readyState=4, status=200, statusText="success"}
parsererror
Error: jQuery110207276483389928793_1377030169256 was not called

firebug 的“net”区域显示 url 是: http://mydomain.com/return_json? callback=jQuery110209170565296948737_1377029879665&_=1377029879666

它还显示响应中包含有效的 JSON。它甚至有一个带有漂亮输出的 JSON 部分。所以,显然我的问题是 jQuery 自动生成的回调函数在那里,但没有被调用。我使用为 jsonp 设置的 $.ajax 和 $.getJSON 方法得到了相同的结果。在这一点上我唯一能想到的就是我应该在发送方以某种方式将 json 数据包装在一个函数中,但我的印象是接收方会处理这个问题。如果有人能看到我做错了什么,将不胜感激。

==================================更新完整答案============= ===========

Hamish 在下面有正确的答案,尽管它只需要两个小调整。以下是使用 Django 以 JSONP 格式发送数据的方法:

def return_json(request):
#                      ^--------I didn't need a parameter in this situation
json_data = ["one", "two", "three"]

return render_to_response("uitest/jsonp_template.html", Context({
    'callback': request.GET.get('callback'),
    'json': mark_safe(json.dumps( json_data )),
#                ^------------------------------This keeps your JSON from getting mangled in 
#                                               URL                                                      
}), mimetype="application/javascript")
#^---------------------This closing parentheses was missing in Hamish's answer at the time
#                      of this writing.                                         
4

1 回答 1

0

JSONP响应实际上是脚本响应 - 类似于:

callbackFunctionName([{'testing': 'testing'}, {'one': 1, 'two': 2, 'three': 3}]);

创建一个模板,该模板application/javascript通过函数调用返回响应,以request.GET.get('callback')JSON 的主体作为唯一参数的函数。

就像是:

def return_jsonp(request, json_data)
    return render_to_response("jsonp_template.html", Context({
        'callback': request.GET.get('callback'),
        'json': json.dumps(json_data),
    }, mimetype="application/javascript")

刚刚在哪里jsonp_template.html

{{ callback }}({{ json }});
于 2013-08-20T21:20:31.553 回答