[英]jsonp callback function not getting called with jQuery
我搜尋了這個網站以及其他地方,以解決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
螢火蟲的“網絡”區域顯示網址為: http://mydomain.com/return_json? callback=jQuery110209170565296948737_1377029879665&_=1377029879666
: http://mydomain.com/return_json? callback=jQuery110209170565296948737_1377029879665&_=1377029879666
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.
JSONP
響應實際上是腳本響應-類似於:
callbackFunctionName([{'testing': 'testing'}, {'one': 1, 'two': 2, 'three': 3}]);
創建一個模板,該模板返回帶有對function request.GET.get('callback')
的函數調用的application/javascript
響應,並將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 }});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.