【问题标题】:sending json data from django-view to ajax将 json 数据从 django-view 发送到 ajax
【发布时间】:2015-10-07 04:18:36
【问题描述】:

我正在尝试使用 ajax 将 json 数据从 django 视图传输到模板。
这里是我的ajax code

$(document).ready(function(){
    console.log("this is getting executed")
    $.ajax({
           url: "/get_ecommdata/",
           type: "get",
           cache: "false",
           dataType : 'json',
           success: function(data) {
              console.log("This is working fine")
              alert(data)
           },
           error:function(xhr, ajaxOptions, thrownError) {
              console.log("this is error")
                alert(xhr.status)
           },
  })
});

如下图:

def get_ecommdata(request):
    print "inside get_ecommdata"
    tempdata = ['{"square": 0, "key": 0}', '{"square": 1, "key": 1}', '{"square": 4, "key": 2}']
    return HttpResponse(tempdata)

状态码为200,但控制台仍显示“这是错误”,即其执行错误部分。

这是我的理解:

状态码为 200,即服务器正在正确发送数据,但在识别数据类型时存在一些问题。 此代码适用于简单文本,但不适用于 json。

我的问题

谁能给我一些关于将 json 数据从 django-view 传递到 ajax 的指导。我想我在这里犯了一些愚蠢的错误。

附:我浏览过其他类似的帖子(json、ajax、view),但没有一个适合这个特定问题。

【问题讨论】:

标签: json ajax django django-views


【解决方案1】:

导入json模块

import json

然后在你的请求方法中试试这个

data = json.dumps([{"square": 0, "key": 0}, {"square": 1, "key": 1}, {"square": 4, "key": 2}])    

return HttpResponse(data, content_type="application/json")

注意

在你的 sn-p 中使用单引号会导致以下输出

'["{\\"square\\": 0, \\"key\\": 0}", "{\\"square\\": 1, \\"key\\": 1}", "{\\"square\\": 4, \\"key\\": 2}"]'

它对寻求者来说很困惑,因此我使用了上述方法。但这取决于选择。

【讨论】:

  • 感谢您的解决方案。使用 json.dumps 确实解决了我的问题。作为记录。问题出在 django-view 中。这是运行良好的更新代码。 def get_ecommdata(request): print "inside get_ecommdata" tempdata = ['{"square": 0, "key": 0}', '{"square": 1, "key": 1}', '{"square": 4, "key": 2}'] # tempdata = "hello" tempdata1 = json.dumps(tempdata) return HttpResponse(tempdata1,content_type="application/json")
  • 精湛 :-),但我仍然建议避免使用引号,因为它会导致结果中出现不必要的 \\。您可以在您的情况下看到 json.dumps 的结果,它会包含令人困惑的双斜杠。但是,如果您对此表示满意,那就太好了:-)但是作为答案,我认为我们应该让他们知道。怎么说?
【解决方案2】:
def get_ecommdata(request):
    print "inside get_ecommdata"
    list_square = [
        {"square": 0, "key": 0},
        {"square": 1, "key": 1},
        {"square": 4, "key": 2}
    ]
    data = json.dumps(list_square)
    return HttpResponse(data, content_type='application/json')

【讨论】:

    猜你喜欢
    • 2015-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-22
    • 2020-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多