2012-07-14 4 views
0

아래에서 반환 된 JSON의 객체에 액세스하려면 어떻게해야 성공 콜백 함수를 코딩해야합니까? 분명히 더 이상 success: function(data) {if (data.returned === true) {을 사용하여 반환 된 객체에 액세스 할 수 없습니다. 나는 어떻게 이것을 성취 할 것인가?다중 반환 데이터 구조에서 JSON 객체에 액세스

jQuery를 코드 :

$("#projects").click(function() { 
       jQuery.ajax({ type: "POST", dataType: "JSON", 
        url: "<?=base_url()?>index.php/home/projectsSlider", 
        json: {returned: true}, success: function(data) { 
         if (data.returned === true) { 
          $("#resultProjects").html(JSON.stringify(data.Projects)); 
          $("#resultScreenshots").html(JSON.stringify(data.Screenshots)); 

          $("#content").fadeOut(150, function() { 
           $(this).replaceWith(projectsSlider(data.projectId, data.projectName, data.startDate, data.finishedDate, data.projectDesc, data.createdFor, data.contributors, data.screenshotURI, data.websiteURL), function() { 
            $(this).fadeIn(150); 
           }); 
          }); 
         } 
        } 
       }); 
      }); 

반환 된 JSON : 내가 제대로 문제를 이해하지만, 당신이 JSON을 호출 할 때 원래 JSON 영구적으로 수정 얻을 수 있다는 우려 보인다 확실하지

{ 
    "Projects": [ 
     { 
      "projectId": "932713684f9073189ec7b", 
      "projectName": "Cloud859Collective", 
      "startDate": "April 19th, 2012", 
      "finishedDate": "April 25th, 2012", 
      "createdFor": "ClasskCreations", 
      "contributors": "Mike Grigsby", 
      "projectDesc": "This website was created with a friend in mind. His name is Kevin Johnson and he is a rapper. He needed a website that would allow him to host and share his music." 
     }, 
     { 
      "projectId": "10599012654f907093714e9", 
      "projectName": "Nurbell Studio", 
      "startDate": "April 15th, 2012", 
      "finishedDate": "April 19th, 2012", 
      "createdFor": "Nurbell LLC", 
      "contributors": "Mike Grigsby", 
      "projectDesc": "This is the page you are currently looking at. This is the official Nurbell homepage. Complete with a frontend and a backend." 
     } 
    ], 
    "Screenshots": [ 
     { 
      "screenshotURI": "http://nurbell.com/vd/1.0/images/project-data/kevo.png" 
     }, 
     { 
      "screenshotURI": "http://nurbell.com/vd/1.0/images/project-data/nurbell.png" 
     } 
    ] 
} 

답변

2

난 당신이 여기에 물어 모르겠어요. 자바 스크립트 네임 스페이스를 살펴 봐야한다고 생각합니다. 그렇게하면 객체 (또는 네임 스페이스)에 속성을 만들고 해당 속성에 json 결과를 넣을 수 있습니다. 이 같은

뭔가 : 당신이 그것을 삭제하거나 페이지를 다시로드 할 때까지

var myProjects = { 
    projects: null, 

    getProjects: function() { 
      // do the ajax thing with something like 
      myProjects.projects = data.projects; 
    }, 

    placeProjects: function() { 
      if (myProjects.projects == null) myProjects.getProjects(); 
      $.each(myProjects.projects, function(i,e){ 
       //place project content 
      } 
    }, 
} 

// define the click event 
$("#projects").click(myProjects.placeProjects()); 

데이터가 저장됩니다. 당신은 당신의 불똥 벌레에있는 DOM 검사기에서이 객체를 볼 수 있습니다. 나는이 jsFiddle http://jsfiddle.net/BTbJu/5 실행 그것에서 아이디어를 구현했습니다

, 첫 번째 프로젝트를로드 사업부 INT 텍스트를 클릭 : 그

EDIT 도움이되기를 바랍니다. 계속 회전하려면 클릭하십시오.

+0

http://pastebin.com/j6XncXmd - 이와 비슷한 기능이 있습니까? '잡히지 않는 구문 오류 : 예기치 않은 토큰}'오류가 발생합니다. 또한'projectsSlider()'에서'data.projectId'에 어떻게 접근해야합니까? –

+0

잘, 각 함수는 첫 번째 인수 (myProjects.projects)의 배열에있는 모든 요소를 ​​반복 한 다음 두 개의 매개 변수가있는 명명되지 않은 함수에 해당 요소를 전달합니다. i = 배열 ​​요소의 인덱스 (예 : myProjects.projects [i]와 같은 것을 변경하고 두 번째 요소는 요소의 내용입니다. 그래서 당신은 e.projectId ....에 의해 projectId를 참조 할 수 있습니다. (함수 인수에서 e를 데이터의 이름으로 바꿀 수도 있지만, 그렇게되면 혼란 스러울 것입니다. http://pastebin.com/PiDBBB0S – Jeroen

+0

은 다른 오타를 발견했습니다. 또한 가독성을 위해 들여 쓰기가 변경되었습니다 : http://pastebin.com/AcDBKtCR – Jeroen

0

.stringify.

아니요, JSON.Stringify는 새 문자열을 반환합니다. 클로저 인수 'data'에 의해 참조 된 원래 json은 그대로 유지됩니다. 데이터 참조를 통해 모든 속성에 액세스 할 수 있습니다.

사실 data.projectId는 클로저 범위 내에서 잘못 될 것이므로 undefined로 평가해야합니다.

이 시도 :

$("#projects").click(function() { 
    jQuery.ajax({ 
     type: "POST", 
     dataType: "JSON", 
     url: "<?=base_url()?>index.php/home/projectsSlider", 
     success: function (data) { 
      var projects = data.Projects; //array 
      var screenshots = data.Screenshots; //array 

      //direct, one-off indexed 
      console.log(projects[0].projectId); 
      console.log(data.Projects[0].projectId); 

      //looped with map 
      projects.map(function(project, index) { 
       console.log(project.projectId); 
      }); 

      //traditional for 
      for(var i1 = 0; i1 < projects.length; i1++) { 
       console.log(projects[i1]); 
      } 

      //direct, one-off indexed 
      console.log(screenshots[0].screenshotURI); 
      console.log(data.Screenshots[0].screenshotURI); 

      //looped 
      screenshots.map(function(screenshot, index) { 
       console.log(screenshot.screenshotURI); 
      }); 

      if (data.returned === true) { 
       //your stringify code etc. 
      } 
     } 
    }); 
}); 
+0

그러면 새 구조에 어떻게 액세스합니까? 나는이 부분을 완전히 뒤 졌어. –

+0

그것은 data.Projects.projectId와 같은 것이거나 비슷한 것입니까? –

+0

아니오, 직접 데이터를 사용합니다. 프로젝트 [0] .projectId. 더 나은 방법은 Projects 배열에 루프를 돌리는 것입니다. –

관련 문제