我已经搜遍了这个网站和其他地方试图解决我与jsonp有关的问题。要开始做事了,下面是我的代码:jsonp回调函数没有被jQuery调用
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
网址是发送JSON数据如下方式Django的网站:
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
萤火虫的“净”区显示的网址是: http://mydomain.com/return_json? callback=jQuery110209170565296948737_1377029879665&_=1377029879666
这也表明,有效的JSON是响应。它甚至有一个JSON部分,它有一个非常好的输出。所以,显然我的问题是,jQuery自动生成的回调函数在那里,但没有被调用。我使用为jsonp设置的$ .ajax和$ .getJSON方法获得了相同的结果。我现在唯一能想到的是,我应该在发送端以某种方式将json数据包装到函数中,但我的印象是接收者需要处理这个问题。如果任何人都可以看到我做错了什么,那将是非常感谢。
=================================更新完整答案========= ===============
Hamish在下面有正确的答案,虽然它只需要两个小调整。下面是如何使用发送JSONP格式数据的Django:
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不返回JSON。 JSONP返回一个函数调用,并将JSON传递给它。你的回答应该是'jQuery1239823492834(你的JSON在这里);',通过使用'request'和获得“回调”项来获得函数的名字。然后,按照我刚才提到的格式生成响应 – Ian