2014-09-26 96 views
0

我使用jQuery和AJAX從我的api獲取一堆結果。轉換從AJAX請求返回的JSON數據

這得到所有考試

$.fn.examEvents = (function() { 
     return $.ajax("/api/scores/exams", { 
      type: "GET", 
      data: JSON.stringify(this), 
      contentType: "application/json", 
      success: function(data, status, XHR) { 
       getScores(data); 
      } 
     }); 

    }); 

這是我的回調函數 這得到了一堆看起來像這樣在我的控制檯對象:

[ 
Object { id="1", examTitle="exam I", startTime="1-1-2014T09:20:00", endTime="1-1-2014T011:20:00"} 
Object { id="2", examTitle="exam II", startTime="1-2-2014T09:20:00", endTime="1-2-2014T011:20:00"} 
Object { id="3", examTitle="exam III", startTime="1-3-2014T09:20:00", endTime="1-3-2014T011:20:00"} 
] 


    function getScores(response) { 
     console.log(response); 
     //this writes out everything as a bunch 
     //of response objects to the console that 
     //contain properties(id, examTitle, startTime, endTime) 

     //transform them 
     var evt = { 
      title: response.examTitle, 
      start: response.startTime, 
      end: response.endTime 
     }; 
     console.log(evt.title);  
     //this is undefined, even though the response 
     //objects contains a property called 'title' so I 
     //was expecting my console to be filled with a 
     //bunch of event titles. 
    }; 

因此,「工作」,意義它正在獲取數據。

但我想包裝並將該數據 轉換成另一個名爲'evt'的對象,但總是返回undefined。

所以我希望能夠做到這一點:

console.log(evt.title); 
console.log(evt.start); 
console.log(evt.end); 

等等

所以我的問題是,我該怎麼辦呢?

謝謝!

回答

3

它是由Ajax調用返回的對象的數組,你必須重複它來獲得物品:

function getScores(response) { 

$.each(response, function (index, item) { 

    var evt = { 
     title: item.examTitle, 
     start: item.startTime, 
     end: item.endTime 
    }; 

    console.log(evt.title); 

}) 
} 

,或者你可以訪問使用索引項,我寫取得數組的第一個項目:

function getScores(response) { 

var evt = { 
      title: response[0].examTitle, 
      start: response[0].startTime, 
      end: response[0].endTime 
     }; 

     console.log(evt.title); 
} 
+0

哇,那很容易。謝謝! – SkyeBoniwell 2014-09-26 16:15:09

+1

很高興幫助@ 999cm999 .... :) – 2014-09-26 16:15:49