2014-09-26 92 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