Reputation: 7092
I'm using jQuery and AJAX to get a bunch of results back from my api.
this gets all the exams
$.fn.examEvents = (function () {
return $.ajax("/api/scores/exams", {
type: "GET",
data: JSON.stringify(this),
contentType: "application/json",
success: function(data, status, XHR) {
getScores(data);
}
});
});
this is my callback function This gets a bunch of objects that look like this in my console:
[
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.
};
So it 'works', meaning it's getting the data.
But I want to wrap and transform that data into another object called 'evt' but that is always coming back undefined.
So I want to be able to do this:
console.log(evt.title);
console.log(evt.start);
console.log(evt.end);
etc...
So my question is, how do I do this?
Thanks!
Upvotes: 0
Views: 711
Reputation: 62488
It is an array of object returned by the ajax call, you have to iterate it to get the items:
function getScores(response) {
$.each(response, function (index, item) {
var evt = {
title: item.examTitle,
start: item.startTime,
end: item.endTime
};
console.log(evt.title);
})
}
or you can access items using index, i am writing for getting first item of array:
function getScores(response) {
var evt = {
title: response[0].examTitle,
start: response[0].startTime,
end: response[0].endTime
};
console.log(evt.title);
}
Upvotes: 3