我已經搜遍了這個網站和其他地方試圖解決我與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