gpt4 book ai didi

javascript - 如何获取 JSONP 数据作为 javascript 对象

转载 作者:行者123 更新时间:2023-11-30 10:14:36 24 4
gpt4 key购买 nike

我正在尝试获取 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"}]);

最佳答案

你只需在回调中设置它:

var employees;

$.ajax({
type: 'GET',
url: url,
contentType: "application/json",
dataType: 'jsonp',
success: function(data) {
employees = data;
}
});

关于javascript - 如何获取 JSONP 数据作为 javascript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24559918/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com