首页 文章

Django视图无法在ajax成功时返回json?

提问于
浏览
3

我已经尝试了JsonResponse和HttpResponse(以及json.dumps)但是即使ajax返回成功,返回的json也无法被$ .parseJSON(returned_json)解析 .

我确信问题不在于通过在终端中打印出json.dumps值并将值复制到变量并将其赋予$ .parseJSON来解析($ . parseJSON(returned_json)),并且它已成功解析它 .

我试图传递最简单的json,但它也失败了我在下面显示的例子:在views.py中

from django.http import JsonResponse

在我看来是处理ajax:

return JsonResponse({"stat":"Success"})

在我的ajax文件中:

$.ajax({
    url:"feed/get_comments/",
    type: "GET",
    data:{c_id: cid}, //cid is a variable initialized above and not creating any problem
    success: function(ret_json){
        alert("Inside success"); //Running everytime
        var sam_json = '{"stat":"Success"}'; //same as what is given in JsonResponse
        var data = $.parseJSON(ret_json); //for debugging change to sam_json
        alert(data); //with sam_json alerting with dictionary, with ret_json not giving any alert
    },

而不是JsonResponse如果我使用json.dumps和HttpResponse同样的事情正在发生 . 从上面我只能得出结论,JsonResponse和HttpResponse没有以json格式返回数据,即使json.dumps成功转换为json格式(因为我复制了这个并粘贴在ajax变量中) . 请帮忙 .

2 回答

  • 2

    不需要 parseJSON .

    由于您只是使用字典,您可以像访问javascript中的任何其他字典一样访问它

    例如 .

    alert(ret_json.stat);
    
  • 1

    使用HttpResponse和json dump,您可以像这样在js中获取响应数据

    var val = $.ajax({
        url:"feed/get_comments/",
        type: "GET",
        data:{c_id: cid}, //cid is a variable initialized above and not creating any problem
        success: function(ret_json){
            alert("Inside success"); //Running everytime
            var sam_json = '{"stat":"Success"}'; //same as what is given in JsonResponse
            var data = jQuery.parseJSON(val.responseText); //for debugging change to sam_json
            alert(data); //with sam_json alerting with dictionary, with ret_json not giving any alert
         },
    

    val.responseText 将包含您从视图发送的数据 .

相关问题