为什么我的 Django jQuery.ajax 响应为空
我试图通过 ajax 调用从 Django 视图调用返回 JSON 响应,如下所示:
var tab = 'test';
var response = $.ajax({
url: "/" + tab + "/"
}).responseText;
alert(response);
这是我的 Django 视图:
if request.is_ajax() == True:
req = {}
req['html'] = '<b>This is a test</b>'
response = simplejson.dumps(req)
print response
return HttpResponse(response, mimetype="application/json")
else:
return render_to_response("ajax/pingpong.html", {'ajax': ajax})
由于某些奇怪的原因,警报框为空(尽管它没有说未定义)。有趣的是,$.post 和 $.getJSON 在完全相同的 URL 上工作得很好。我还在控制台上看到了预期的 JSON 输出。任何帮助将不胜感激!
I'm trying to return a JSON response from a Django view call via an ajax call like below:
var tab = 'test';
var response = $.ajax({
url: "/" + tab + "/"
}).responseText;
alert(response);
Here is my Django view:
if request.is_ajax() == True:
req = {}
req['html'] = '<b>This is a test</b>'
response = simplejson.dumps(req)
print response
return HttpResponse(response, mimetype="application/json")
else:
return render_to_response("ajax/pingpong.html", {'ajax': ajax})
For some odd reason, the alert box is blank (though it does not say undefined in it). Interestingly enough, $.post and $.getJSON work fine on the exact same URL. I also see the expected JSON output on my console. Any help would be appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
除非我弄错了,否则
responseText
不是$.ajax()
返回的属性。我认为你必须这样做:由于
dataType
参数,成功回调产生的数据是一个普通的 JS 对象。如果您不指定dataType
,您将获得包含服务器返回的原始内容的字符串。Unless I am mistaken,
responseText
isn't an attribute on whatever$.ajax()
returns. I think you have to do something like this:Because of the
dataType
parameter, the data yielded to the success callback is a normal JS object. If you don't specify thedataType
, you'll get the string with the raw content the server returns.您没有将
dataType
参数设置为json
,并且您需要从 success 函数获取 json 对象,请尝试以下操作:You're not setting the
dataType
parameter tojson
, and you'll need to get the json object from the success function, try this:尽管文档声称 ResponseText 将阻止浏览器直到请求完成,但在我看来,您遇到了竞争条件,即您在 XHR 请求完成之前警告变量。你必须做这样的事情:
Although the documentation claims ResponseText will block the browser until the request is complete it appears to me like you're getting a race condition, i.e your alerting the variable before the XHR request is complete. You'll have to do something like this:
试试这个:
Try this instead:
我遇到了同样的问题,但仅在特定环境下。我想知道你的问题是否相同。我的环境:
在这种情况下,以下 jQuery 代码大约有一半的时间会导致 data = null, status = "success"。另一半时间它返回数据的有效对象。
I'm having the same issue but only under a specific environment. I'm wondering if your issue is the same. My environment:
Under those circumstances, the following jQuery code leads to data = null, status = "success" around half the time. The other half the time it returns a valid Object for data.