没有用jQuery调用jsonp回调函数

jsonp callback function not getting called with jQuery

本文关键字:回调 函数 jsonp 调用 有用 jQuery      更新时间:2023-09-26

我已经搜索了这个网站和其他地方,试图解决我在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_json url是一个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数据封装在发送方的函数中,但我认为接收方会处理好这一点。如果有人能看到我做错了什么,我将不胜感激。

====================================使用完整答案更新====================

哈米什在下面给出了正确的答案,尽管它只需要两个小的调整。以下是如何使用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.                                         

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 }});