【问题标题】:retrieving elements from data returned as json from django view从 django 视图中以 json 形式返回的数据中检索元素
【发布时间】:2012-05-25 06:18:12
【问题描述】:

在我的django 视图中,我使用simplejson 将一些搜索结果转换为json

vals = [('supposed to be a toaster.', 8),('we can do more than one thing.',14),("we could make a bicycle.",51)]

result={'results':vals}

serialized = simplejson.dumps(result)

序列化=>

{"msg": "success!.",  "results": [["supposed to be a toaster.", 8], ["we can do more than one thing.", 14], [" we could make a bicycle.", 51]]}

我可以通过

将此序列化数据发送到javascript函数
return HttpResponse(serialized, mimetype="application/json")

在我的 javascript 函数中(使用 jquery),我可以将数据检索为

var data = $.parseJSON(res.responseText);
var results = data['results']

我想以以下格式显示结果

8  -- supposed to be a toaster. 
14 -- we can do more than one thing
51 -- we could make a bicycle

如何在 javascript 中做到这一点? javascript变量results包含s

supposed to be a toaster.,8,we can do more than one thing.,14,we could make a bicycle.,51,

我是否必须使用regex 来分隔项目?或者有更好的解决方案吗?使用正则表达式的困难在于, 字符串有时可能包含数字。

编辑

感谢 Priyank 和 alexey28 的回复,我试过了

for(var item in results) {
    var time = results[item][1];
    console.log('time='+time);
    var resStr =results[item][0];
    console.log('resStr='+resStr);
    formatedResult += time+ " --- " + resStr+'<br>';
}
$('#showresults').html(formatedResult);

【问题讨论】:

  • 我认为您可以通过使用简单的 javascript for 循环来迭代数据['results']。控制台“数据”..并在萤火虫中看到你所看到的......
  • 感谢 Priyank,这会起作用

标签: javascript python ajax django


【解决方案1】:

变量数据将包含数组,因此您可以:

var formatedResult = "";
for(var i = 0; i < data.length; i++) {
    var item = data[i];
    formatedResult += item[1] + " --- " + item[0];
}
// Set html for you <div id="resultOutput"></div>:
jQuery("div#resultOutput").html(formatedResult);

【讨论】:

  • 嗨,我稍微修改了您的解决方案并使其正常工作..请查看我编辑的问题
猜你喜欢
  • 2020-11-07
  • 2020-06-29
  • 1970-01-01
  • 1970-01-01
  • 2011-06-11
  • 2021-01-21
  • 1970-01-01
  • 2011-06-21
  • 1970-01-01
相关资源
最近更新 更多