我试图获取JSONP数据,以便我可以在javascript中解析它。我有一些我可以解析的模拟数据,如下所示:
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" }
];
但是当我尝试使用JSONP从另一台服务器上的RESTful API获取相同的数据时,它不起作用。我希望能够以与模拟数据相同的格式获取数据。我不知道我请求它的方式是否错误,但这是我怀疑的,因为数据存在,并且采用JSONP格式。以下是我要求它的方式:
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
}
});
谢谢你看看。
修改:当您点击此链接http://marketing.wasatchtechies.com/api/JSONraces?callback=foobar时,您会收到以下信息:
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"}]);
答案 0 :(得分:3)
您只需在回调中设置它:
var employees;
$.ajax({
type: 'GET',
url: url,
contentType: "application/json",
dataType: 'jsonp',
success: function(data) {
employees = data;
}
});
答案 1 :(得分:1)
您缺少回调方法
ajax请求中的成功和错误方法。 像这样的东西
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
}
});