2009-09-27 3 views
-1

나는 jquery .ajax 호출을 만들고 나는 json 결과를 기대하고있다. catch가 5 명의 작성자가 있다면 author_details_0, author_details_1, author_details_2 등을 얻을 수 있습니다. json에서 검색 할 변수의 이름을 동적으로 구성하려면 어떻게해야합니까? 내가 얼마나 많은 작가를 사귈 지 모르지만, 수백 명이있을 수 있습니다.Jquery Json 동적 변수 이름 생성

$.ajax({ 
type: "POST", 
url: "/authordetails/show_my_details/", 
data: af_pTempString, 
dataType: "json", 
beforeSend: function() { 
}, 
success: function(jsonData) { 
    console.log("Incoming from backend : " + jsonData.toSource()); 
    if(jsonData.AuthorCount) 
    { 
     console.log("Number of Authors : " + jsonData.AuthorCount); 
     for (i = 0; i < jsonData.AuthorCount; i++) 
     { 
      temp = 'author_details_' + i; <-------------------This is the name of the variable I'm expecting. 
      console.log("Farm information : " + eval(jsonData.temp)); <----- This doesn't work, how can I get jsonData.author_details_2 for example, 'coz I don't know how many authors are there, there could be hundreds. 
     } 
    } 

해결 방법에 대한 의견이 있으면 알려 주시기 바랍니다. 많은 감사하겠습니다.

+0

을 왜 등 author_details_0, 1, 2, 필요합니까? – yoda

+0

json을 어떻게 생성합니까? – Eric

+0

백엔드에서 django를 사용하고 있습니다. 내가 만든 데이터 모델에는 Author 및 관련 Author_Details 테이블이 있습니다. 게시자 ID가 주어지면 필자는 json_serializer.serialize (allAuthors, ensure_ascii = False)를 간단히 직렬화하는 Authors 집합을 쿼리하고 가져옵니다. 이것은 저자 세부 정보를 직렬화하지 않으므로 저자 객체 배열을 반복하고 수동으로 작성해야합니다. 따라서 author_details_XX는 저자 기본 키입니다. 저자 및 기타 세부 정보를 단일 JSON Array 객체로 묶는 방법이 있는지 잘 모르겠습니다. 기쁜 마음으로 내 코드를 개조 해 보겠습니다. – PlanetUnknown

답변

5

두 가지 방법으로 개체 속성에 액세스 할 수 있습니다. 첫 번째는 object.property 에서처럼 점 표기법입니다. object [ 'property']처럼 대괄호 표기법을 사용할 수도 있습니다. 여기에 평가판 필요 없음 :

var propName = 'author_details_' + i; 
alert('Details for author ' + i + ' = ' + jsonData[propName]; 

This page은 귀하의 가정을 하단에 표시합니다.

+0

그게 효과가 있습니다! 바나바 고마워, 나는 여기서 뭔가를 배웠다! – PlanetUnknown

2

해결했습니다!

대신 "temp"- temp = 'author_details_'+ i; 다음 일 -

그냥이 작품 평가 (jsonData.temp) - 평가 ("jsonData.author_details_"+ I)

데이터가 데이터베이스에서이기 때문에, 그것은 내가 모든 것을 넣어 때문에, 안전 확인 후 데이터베이스에. 따라서 eval은 보안 위협을 제기하지 않습니다.

더 많은 해결 방법이 있으면 알려 주시기 바랍니다.

0

json을 배열로 저장하지 않는 이유는 무엇입니까? 대신 :

{ 
    "author_details_1": 
    { 
     ... 
    }, 
    "author_details_2": 
    { 
     ... 
    }, 
    "author_details_3": 
    { 
     ... 
    }, 
    "author_details_4": 
    { 
     ... 
    } 
    ... 
} 

{ 
    "author_details": 
    [ 
     { 
      ... 
     }, 
     { 
      ... 
     }, 
     { 
      ... 
     }, 
     { 
      ... 
     } 
    ] 
    ... 
} 

을 시도 그럼 당신은 [I] author_details에 액세스 할 수 있습니다.

+0

감사합니다. Eric. 저도 그렇게 해봅시다. – PlanetUnknown

0

jQuery 및 $ .ajax 함수에 문제가 발생했습니다. $ 아약스 기능을 외부에서 '데이터'객체를 정의하여 해결 :

var data = new Object(); 
data.ContentNodeID = button.siblings('.ContentNodeID').val(); 
data.ContentObjectID = button.siblings('.ContentObjectID').val(); 
data.ActionAddToBasket = ''; 
data['eZOption['+$('[name=printFormatAttributeId]').val()+'][]'] = $('.eZOption').val(); 

$.ajax({ 
    cache: false, 
    type: 'POST', 
    url: button.parent().attr('action'), 
    data: data, 
    success: function(data){ 
       button.siblings('.addtobasket_success').css('display', 'inline'); 
       $('#shop_button').removeClass('disabled'); 
       $('#shop_button').removeAttr('disabled'); 
      }, 
    error: function(data) { 
       button.siblings('.addtobasket_failure').css('display', 'inline'); 
      } 
}); 
0
url = './json/demo_'+var+'.net'; 
$.getJSON(url, function(result){ 
    alert(result[0].name); 
}); 

또는

$.getJSON('./json/demo_'+var+'.net', function(result){ 
    alert(result[0].name); 
});