4

我正在尝试通过 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 输出。任何帮助,将不胜感激!

4

5 回答 5

2

您没有将dataType参数设置为json,您需要从成功函数中获取 json 对象,试试这个:

var tab = 'test';
$.ajax({
    url: "/" + tab + "/",
    dataType: "json",
    success: function(json){
        alert(json);
    }        
});
于 2009-08-26T12:07:12.540 回答
1

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

$.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.

于 2009-08-26T12:11:59.053 回答
1

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
});
于 2009-08-26T12:26:34.917 回答
1

Try this instead:

var tab = 'test';
var response = $.ajax({
    url: "/" + tab + "/",
    success: function(data, textStatus) { alert(data); }
});
于 2009-08-26T12:29:30.610 回答
0

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.");
   } 
});
于 2010-03-10T10:11:45.310 回答