为什么我的 Django jQuery.ajax 响应为空

发布于 2024-08-03 04:24:52 字数 627 浏览 7 评论 0原文

我试图通过 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

西瓜 2024-08-10 04:24:52

除非我弄错了,否则 responseText 不是 $.ajax() 返回的属性。我认为你必须这样做:

$.ajax({
  url: "/test",
  dataType: "json",
  success: function(data) {
    // use data
  }
});

由于 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:

$.ajax({
  url: "/test",
  dataType: "json",
  success: function(data) {
    // use data
  }
});

Because of the dataType parameter, the data yielded to the success callback is a normal JS object. If you don't specify the dataType, you'll get the string with the raw content the server returns.

往事风中埋 2024-08-10 04:24:52

您没有将 dataType 参数设置为 json,并且您需要从 success 函数获取 json 对象,请尝试以下操作:

var tab = 'test';
$.ajax({
    url: "/" + tab + "/",
    dataType: "json",
    success: function(json){
        alert(json);
    }        
});

You're not setting the dataType parameter to json, and you'll need to get the json object from the success function, try this:

var tab = 'test';
$.ajax({
    url: "/" + tab + "/",
    dataType: "json",
    success: function(json){
        alert(json);
    }        
});
梦中楼上月下 2024-08-10 04:24:52

尽管文档声称 ResponseText 将阻止浏览器直到请求完成,但在我看来,您遇到了竞争条件,即您在 XHR 请求完成之前警告变量。你必须做这样的事情:

var complete = function(data) {
    console.log(response.responseText);
}
var tab = 'test';
var response = $.ajax({
    url: "/" + tab + "/",
    dataType: "json",
    success : complete
});

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:

var complete = function(data) {
    console.log(response.responseText);
}
var tab = 'test';
var response = $.ajax({
    url: "/" + tab + "/",
    dataType: "json",
    success : complete
});
乖不如嘢 2024-08-10 04:24:52

试试这个:

var tab = 'test';
var response = $.ajax({
    url: "/" + tab + "/",
    success: function(data, textStatus) { alert(data); }
});

Try this instead:

var tab = 'test';
var response = $.ajax({
    url: "/" + tab + "/",
    success: function(data, textStatus) { alert(data); }
});
情深如许 2024-08-10 04:24:52

我遇到了同样的问题,但仅在特定环境下。我想知道你的问题是否相同。我的环境:

  1. 运行 Django 的内部网络服务器 (./manage.py runserver 0.0.0.0:8080)
  2. 在 Google Chrome 中查看我的网站 (v4.1.249.1025)。

在这种情况下,以下 jQuery 代码大约有一半的时间会导致 data = null, status = "success"。另一半时间它返回数据的有效对象。

$.ajax({
   type:"POST",
   url:"response/"+q.id+"/",
   cache:false,
   dataType:"json",
   data:{response:$(this).val()},
   success:function(data, status) {
     alert(data+","+status);
   }, 
   error:function() {
     $(".main_container").text("Error. Please check your internet connection.");
   } 
});

I'm having the same issue but only under a specific environment. I'm wondering if your issue is the same. My environment:

  1. Running Django's internal webserver (./manage.py runserver 0.0.0.0:8080)
  2. Viewing my website in Google Chrome (v4.1.249.1025).

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.

$.ajax({
   type:"POST",
   url:"response/"+q.id+"/",
   cache:false,
   dataType:"json",
   data:{response:$(this).val()},
   success:function(data, status) {
     alert(data+","+status);
   }, 
   error:function() {
     $(".main_container").text("Error. Please check your internet connection.");
   } 
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文