【发布时间】: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