Reputation: 14589
I'm trying to get JSONP data so I can parse it in javascript. I have some mock data that I am able to parse which looks like this:
var employees = [
{ "Cost": 50, "Date": "2014-05-25T00:00:00", "Distance": "5k", "Id": "137", "Location": "Salt Lake City", "Name": "Employee 1", "Type": "normal" },
{ "Cost": 50, "Date": "2014-05-25T00:00:00", "Distance": "5k", "Id": "138", "Location": "Provo", "Name": "Employee 2", "Type": "normal" },
{ "Cost": 50, "Date": "2014-05-25T00:00:00", "Distance": "5k", "Id": "139", "Location": "Ogden", "Name": "Employee 3", "Type": "normal" }
];
But when I try to get the same data from a RESTful API on another server using JSONP it doesn't work. I would like to be able to get the data in the same format as the mock data. I don't know if the way I'm requesting it is wrong, but that is what I suspect because the data is there, and in JSONP format. Here is how I'm requesting it:
var employees;
var url = 'http://marketing.wasatchtechies.com/api/JSONraces/callback=?';
$.ajax({
type: 'GET',
url: url,
async: true,
contentType: "application/json",
dataType: 'jsonp',
success: function (data) {
employees = data;
},
error: function (err) {
// nothing
}
});
Thanks for taking a look.
Edit: when you follow this link http://marketing.wasatchtechies.com/api/JSONraces?callback=foobar you get the following:
foobar([{"id":137,"name":"JE Cosgriff Tiger Trot","location":"Salt Lake City","date":"2014-05-25T00:00:00","url":"http://www.utahrunning.com/events/race/ref/JE-Cosgriff-Tiger-Trot","distance":"5k","cost":"50 ","type":"normal"},{"id":138,"name":"Race for Grief Event","location":"West Bountiful","date":"2014-05-26T00:00:00","url":"http://www.utahrunning.com/events/race/ref/Race-for-Infant--Pregnancy-Loss---10K-run--2-mile-awareness-walk","distance":"5k","cost":"45 ","type":"normal"},{"id":139,"name":"Heber Valley Memorial Run","location":"Heber City","date":"2014-05-26T00:00:00","url":"http://www.utahrunning.com/events/race/ref/Heber-Valley-Memorial-Run","distance":"5k, mile","cost":"35 ","type":"glow"}]);
Upvotes: 1
Views: 208
Reputation: 64657
You just set it in the callback:
var employees;
$.ajax({
type: 'GET',
url: url,
contentType: "application/json",
dataType: 'jsonp',
success: function(data) {
employees = data;
}
});
Upvotes: 3
Reputation: 4824
You are missing the callback method
success and error method in your ajax request. Something like this
var employees = $.ajax({
type: 'GET',
url: url,
async: false,
contentType: "application/json",
dataType: 'jsonp',
success: function(result) {
// access your mock data in result
},
error: function(err) {
// acces err object to handle the error
}
});
Upvotes: 1