我在 python 中创建了一个列表,然后将其转换为 json。但我在 javascript 中迭代并显示正确的项目时遇到了麻烦。
有什么建议吗?
python :
def friends2(request):
fb_feed = [#data in here]
b = json.dumps(fb_feed)
print b
return HttpResponse(b)
当我打印b
时控制台中打印的内容:
[
[1236870349, "Your friend", "Bhangra indian Jingle Bells balle balle Merry Christmas", "2lPdXV1KO4s", "Your friend watched \"Bhangra indian Jingle Bells balle balle Merry Christmas\""],
[2303218, "Your friend", "Look at this Instagram (Nickelback Parody)", "ttp://www.c", "Your friend watched \"Look at this Instagram (Nickelback Parody)\""]
]
JavaScript
<script>
$(document).ready(function (){
event.preventDefault();
$.ajax({
type:"GET",
url:"/friends2/",
data: {},
success: function(b){
b = jQuery.parseJSON(b);
console.log(b) //returns null
for (var i = 0; i < b.length; i++) {
var friend = "";
friend = b[i][3]
friend += "\n";
$('.social').append(friend);
}
}
});
});
</script>
html
<div class = 'social'></div>
最佳答案
将dataType:json
添加到$.ajax
脚本
$.ajax({
type:"GET",
url:"/friends2/", #the url /friends2/ points to friends2 in python
data: {},
dataType: json, //ADD THIS
...
...
如果您不想添加dataType
,那么您可以使用jQuery.parseJSON(b)
来解析您的json字符串,
success: function(b) {
var data = jQuery.parseJSON(b); //parse JSON string here
...
...
}
关于javascript - 我已经在 python 中创建了一个列表,但是如何在 javascript 中迭代这个列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13746821/