Jquery 来自Python Django的JSONP响应
我试图通过将回调追加到响应中,从django视图返回JSONP对象,如下所示:Jquery 来自Python Django的JSONP响应,jquery,python,ajax,django,Jquery,Python,Ajax,Django,我试图通过将回调追加到响应中,从django视图返回JSONP对象,如下所示: def complete(request): prefix = request.GET.get('q','') mode = request.GET.get('mode','') callback = request.GET.get('callback', '') response = completer_func(prefix, inv_indices, trie) if
def complete(request):
prefix = request.GET.get('q','')
mode = request.GET.get('mode','')
callback = request.GET.get('callback', '')
response = completer_func(prefix, inv_indices, trie)
if callback != None:
response = '{0}({1})'.format(callback, response)
return JsonResponse(response, safe=False)
当我在chrome中检查inspect/network下的响应时,它返回类似于“jquery1110037170758636331014_149922434194([u'information technology',u'interior design',u'international',u'industrial design',u'information technology services')”的内容。然而,在客户端,它抛出了一个错误,我将其记录到控制台并显示
readyState: 4
demo.html:91 responseText: undefined
demo.html:92 status: 200
demo.html:93 text status: parsererror
demo.html:94 error: Error: jQuery11110037170758636331014_1499222434194 was not called
我看到了一些其他的帖子,比如解释如何将回调添加到响应中(我做到了)。但不知何故,它似乎不起作用。我已经在下面介绍了jQueryAjax调用
$('#ajax-demo').autoComplete({
minChars: 1,
source: function(term, response){
$.ajax({
dataType: "jsonp",
type: "GET",
url: 'http://localhost:8000/complete/',
data: {
q: term
},
success: function (data) {
},
error: function(xhr,textStatus,err){
console.log("readyState: " + xhr.readyState);
console.log("responseText: "+ xhr.responseText);
console.log("status: " + xhr.status);
console.log("text status: " + textStatus);
console.log("error: " + err);
}
});
}
});
更新1
在回答了这个问题之后,我能够修复这个问题,允许在服务器端使用CORS头,并使用JSON而不是JSONP。但我仍然想知道我的第一个方法出了什么问题 试着返回一个简单的json
,并验证是json搞乱了还是其他东西,比如{“title”:“Person”,“type”:“object”}
我从这里开始!但是尝试返回json
会产生CORS错误:请求的资源上不存在“Access Control Allow Origin”标题
@unn我尝试先直接在浏览器中加载URL,然后再从JavaScript开始工作。@MichaelMior:我确实这样做了!看起来很好。@Unni在JSONP案例中也是这样吗?如果是这样,听起来像是JS问题。尝试返回一个简单的json
,并验证是json搞乱了还是其他什么,比如{“title”:“Person”,“type”:“object”}
我从那里开始!但是尝试返回json
会产生CORS错误:请求的资源上不存在“Access Control Allow Origin”标题
@unn我尝试先直接在浏览器中加载URL,然后再从JavaScript开始工作。@MichaelMior:我确实这样做了!看起来很好。@Unni在JSONP案例中也是这样吗?如果是这样,听起来像是JS问题。