gpt4 book ai didi

javascript - 使用 JSONP 的 AJAX 跨域数据

转载 作者:行者123 更新时间:2023-11-30 18:15:16 25 4
gpt4 key购买 nike

我正在尝试从 Geobytes 获取数据。其中一个模板返回 JSON,我需要跨域访问它。

我写了这两个函数

function getCountry(ip) {
var surl = "http://www.geobytes.com/IpLocator.htm?GetLocation&template=json.txt";
$.ajax({
url: surl,
data: '{"ipaddress":"' + ip + '"}',
dataType: "jsonp",
processData: false,
jsonpCallback: "jsonpcallback",
error: function (xhr, status, error) {
alert(xhr.responseText);
}
});
}

function jsonpcallback(rtndata) {
alert(rtndata.message);
}

调用成功,这些是我的响应头:

HTTP/1.1 200 OK
Date: Sat, 17 Nov 2012 12:43:54 GMT
Expires: 0
Content-type: text/html
Transfer-Encoding: chunked

返回的数据是JSON,但是我得到了

warning: Resource interpreted as Script but transferred with MIME type text/html: "http://www.geobytes.com/IpLocator.htm?GetLocation&template=json.txt&callback=jsonpcallback&{%22ipaddress%22:%22200.167.254.166%22}&_=1353148931121"

Error on the remote IpLocator.htm: Uncaught SyntaxError: Unexpected token :

错误是在返回的数据上抛出的

{"geobytes":{"countryid":117,

我想可能是因为它是 117 而不是“117”,但显然我无法控制返回的数据。尝试添加“processData=false”但没有帮助。

我已经将错误处理添加到 ajax 并在状态上得到“parsererror”

我该如何解决这个问题?

最佳答案

尝试像这样修改字段数据类型:

...dataType: "jsonp json",...

这样你得到的数据就会被解析为json。

遵循文档:

The type of data that you're expecting back from the server. If none is specified, jQuery will try >to infer it based on the MIME type of the response.

在您的情况下,您获得的 MIME 是文本/html,将“json”值添加到数据类型,您告诉 jQuery 将响应视为 json 而不是文本。

如果服务不支持 JSONP,您可以制作自己的代理页面来处理请求,或使用 YQL,如下所述:Cross-Domain request when server does NOT support JSONP

关于javascript - 使用 JSONP 的 AJAX 跨域数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13429873/

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