2014-03-25 3 views
1

보기에서 Django 객체를 가져 오는 Ajax 함수가 있습니다.jQuery에서 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 . 내가 뭘 잘못하고 있니?

편집 :

이 제대로 나는 성공 함수에서 다음과 같이 변경 만든 분야 얻으려면 -

>> [{ "model" : "object.list", "pk" : 1, "fields" : { "name" : "...", ... } }] 
// ^----- Array 

물론 그래서 -

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

장고 dict 개체에는 무엇이 있습니까? JSON 개체는 어떻게 보이나요? '.fields'가 확실합니까? –

+0

@Bibhas 나는 약간의 업데이 트를 확인했다. –

답변

2

당신의 response.user_cards_held 배열 객체입니다 response.user_cards_held.fields은 정의되지 않습니다. 실제 개체는 response.user_cards_held[0]입니다. 따라서 response.user_cards_held[0].fields과 같은 fields 속성에 액세스 할 수 있습니다.

+0

나는 이것을 이미 시도했다. 첫 번째 "[". –

+0

즉'response.user_cards_held'는 JSON 객체가 아닌 JSON 문자열입니다. 먼저 JSON 객체로 파싱해야합니다. –

+0

다른 변수들도 파싱 한 후 많은 도움을주었습니다. –

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**; 
+2

코드가 질문에 대답 할 수 있지만 솔루션이 작동하는 이유 및 관련 참조에 대한 설명을 항상 포함하는 것이 가장 좋습니다. –

+0

@TimHutchison 필자는 "코드를 닫고 표시"방법을 선호합니다. 코드를 주석 처리했습니다. 참조 할 때 참조를 찾지 못했기 때문에 참조는 내 자신의 응용 프로그램입니다. 그러나 나는 이것을 향상 시키려고 노력할 것이다, 고마워. –

관련 문제