我正在使用ajax调用来使用“jsonp”数据类型从错误函数调用来获取跨域url的json数据。我可以在mozilla开发者中看到json数据 - >网络 - >即将到来的回应。下面是代码:
$(document).ready(function() {
$.ajax({
url : 'https://www.example.com /fetchdata?param=1',
type : 'POST',
crossDomain : true,
dataType : 'jsonp',
headers : {
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Methods' : 'POST'
},
jsonpCallback : 'callbackdata',
success : function(data) {
alert("success");
},
error : function(xhr, status, error) {
console.log(error);
alert("fail");
},
});
});
function callbackdata(response) {
alert(response)
}
收到以下错误:
Error: callbackdata was not called
Stack trace:
.error@http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js:2:1821
b.converters["script json"]@http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js:4:16101
uc@http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js:4:7333
x@http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js:4:10747
.send/c@http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js:4:15393
n.event.dispatch@http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js:3:6392
n.event.add/r.handle@http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js:3:3202
CORS:25:7
SyntaxError: missing ; before statement
和mozilla daveloper中的反应 - >网络
{"datapoints": [{"record_timestamp": "10-09-2016 05:30","data": {"temperature": {"id": "3","param_name": "temperature","value": "28.6","unit": "celsius"}}}]}
json数据不与jsonpcallback相关。请帮我找到解决方案。
如果我尝试使用“json”作为dataType而不是“jsonp”进行ajax调用,则服务器会响应
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.example.com/fetchdata?param=1.(Reason: CORS header 'Access-Control-Allow-Origin' missing)
答案 0 :(得分:0)
您要求的服务器需要设置CORS标头,因此无论您的example.com
是什么,都需要将其服务器设置为提供Access-Control-Allow-Origin "*"
标头。将它放在你的AJAX请求中将不起作用。
答案 1 :(得分:0)
您请求数据的服务器返回JSON,而不是JSONP。服务器必须支持JSONP,它要求它返回JavaScript代码,而不是纯JSON。
例如:
JSON是:
"{\"message\":\"hello world\"}"
JSONP是:
callback({message:"hello world"})
当提供'callback'URL参数时,服务器将返回JSONP脚本(jQuery为您提供)。
除非此特定服务器支持此功能,否则不会调用您的回调。
虽然不是jQuery问题,但this Q&A涵盖了同一主题。