没有用jQuery调用jsonp回调函数
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
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 }});
- JavaScript回调函数
- 如何在回调函数中执行流
- 回调函数中传递参数的困难(Google Map API Markers)
- 如何正确地将参数传递给RequireJS回调函数
- 回调函数在python代码中离线
- 从AJAX回调函数中分离数据
- 赋值后的回调函数
- 如何在javascript回调函数中返回多个变量
- 函数表达式,返回回调函数
- 等待回调函数执行
- JavaScript回调函数和Google Feed API
- 如何从ajax成功回调函数中读取javascript变量
- 正在保存JavaScript内部回调函数中的值
- 有没有什么方法可以停止Jquery中的animate(也可以停止完整的回调函数)
- 如何在javascript中添加带有回调函数的按钮点击事件作为window.conf
- 在Golang回调函数中启用CORS
- 在初始函数完成之前调用回调函数
- jQuery Mobile:如何在$.Mobile.changePage之前运行回调函数
- 即使使用回调函数也无法返回值
- 为什么prototypjs观察到回调函数有绑定