转换从AJAX请求返回的JSON数据

时间:2014-09-26 16:05:11

标签: jquery ajax

我正在使用jQuery和AJAX从我的api中获取大量结果。

这可以获得所有考试

    $.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'的对象,但总是回归未定义。

所以我希望能够做到这一点:

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

等...

所以我的问题是,我该怎么做?

谢谢!

1 个答案:

答案 0 :(得分: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);
}