[英]retrieving elements from data returned as json from django view
在我的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);
可變數據將包含數組,因此您可以:
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.