我有一个Ajax函数从视图中获取Django对象。
我想在jQuery中访问该对象的所有属性,但我无法这样做。
$.ajax(
{
url: domain+'/game/android/',
type:"POST",
success:function(response){
response = jQuery.parseJSON(response);
localStorage['userCard'] = response.user_cards_held;
localStorage['compCard'] = response.comp_cards_held;
localStorage['game'] = response.game;
alert(response.user_cards_held);// **this shows all the fields. **
alert(response.user_cards_held.fields);//This does not work. Gives the value as undefined
window.location = 'file:///android_asset/www/game.html';
},
error:function(xhr, status, error){
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
},
});
查看是这样的:
from django.core import serializers
...
json = serializers.serialize('json', objectlists)
return HttpResponse(json, mimetype="application/json")
对象是这样的:
[{ "model" : "object.list", "pk" : 1, "fields" : { "name" : "...", ... } }]
我检查了这个问题:Question Referenced 这不起作用。 我做错了什么?
编辑:
为了正确获得该字段,我在成功函数中进行了以下更改 -
success:function(response){
response = jQuery.parseJSON(response);
localStorage['userCard'] =jQuery.parseJSON(response.user_cards_held);
localStorage['compCard'] = jQuery.parseJSON(response.comp_cards_held);
localStorage['game'] = jQuery.parseJSON(response.game);
alert(jQuery.parseJSON((response.user_cards_held));// **this shows all the fields. **
alert(jQuery.parseJSON(response.user_cards_held.fields));//This does not work. Gives the value as undefined
window.location = 'file:///android_asset/www/game.html';
}
答案 0 :(得分:2)
您的response.user_cards_held
是一个数组对象 -
>> [{ "model" : "object.list", "pk" : 1, "fields" : { "name" : "...", ... } }]
// ^----- Array
所以当然response.user_cards_held.fields
是未定义的。您的实际对象位于response.user_cards_held[0]
,因此您可以访问fields
等response.user_cards_held[0].fields
属性。
答案 1 :(得分:0)
[{ "model" : "object.list", "pk" : 1, "fields" : { "name" : "José", ... } }]
// convert JSON string to JSON Object:<br>
var data = $.parseJSON(response);<br>
// acess name atribute<br>
**data[0].fields.name**;