【问题标题】:Return a a json object from an ajax call to a django view从 ajax 调用返回一个 json 对象到 django 视图
【发布时间】:2014-05-29 22:01:10
【问题描述】:

我正在尝试返回一个 json 对象以呈现到我的模板中的网格。 我就是这样做的。

views.py
def ajax_up(request):
    history_data=Upload_history.objects.all()
    history=serializers.serialize("json",history_data)
    return HttpResponse( history, mimetype='application/json' )
html
 $(".reply").click(function(){

      $.ajax({
    url: "/ajax_up/",
    type: 'GET', //this is the default though, you don't actually need to always mention it
    dataType: "json",
    success: function(data) {
      alert("awasome"+ data)

    },
    failure: function(data) { 
        alert('Got an error');
    }

}); 

所以我声明一个对象来保存数据

var data = {{history|safe}};

如上图所示,从 ajax 调用返回历史记录 但是当我做警报(数据)时,我得到[对象对象],[对象对象]..... 有人可以帮忙吗?

【问题讨论】:

  • {{history|safe}} 的引用是什么?那是一个django模板标签,但是这里没有模板视图。

标签: ajax django


【解决方案1】:

听起来像是在工作,但alert 只显示一个字符串。由于您的数据不是字符串,它会显示[object Object]。

使用JSON.stringify 序列化数据或使用console.log 而不是alert 在浏览器javascript 控制台中查看数据。

【讨论】:

  • 即使在控制台也显示相同!!
  • 我使用 json.stringfy 后,它可以正确显示数据,但数据未解析为 {{history|safe}}
  • “解析为”是什么意思? “历史|安全”在哪里?请注意,您使用的是 django 模板标签 - 它仅适用于 django 呈现的 django 模板。
猜你喜欢
  • 2016-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-28
  • 1970-01-01
  • 2015-07-26
相关资源
最近更新 更多