[英]Using jQuery/Jsonp to send cross-domain request and parse result?
我正在尝试使用jQuery从远程跨域站点获取和解析数据。为避免Same-Origin-Policy和Cross-Domin问题,我使用jsonp。
<html>
<head>
<title>Ajax Sample</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.min.js"></script>
</style>
<script>
$(document).ready(function(){
//Obviously the service wont give a JSON format response
var url='http://stackoverflow.com/search?q=Cross+domain';
$.ajax({
url:url,
dataType: 'jsonp',
success:function(data){
console.log(data);
},
error:function(){
alert("Error");
},
});
});
</script>
<body>
</body>
</html>
但是我得到的是error
:
Resource interpreted as Script but transferred with MIME type text/html: "http://stackoverflow.com/search?q=Cross+domain&callback=jQuery1708665772899985313_1374154944485&_=1374154944492"
和
Uncaught SyntaxError: Unexpected token <
那么如何以正确的方式做到这一点呢?
如果远端未为其JSONP输出设置正确的Content-Type
标头,则第一个警告是正常的。 这只是警告,不会造成伤害。
如果第二个错误是由于尝试访问stackoverflow网站而引起的,那么该错误仅是因为您试图在JS解释器上抛出HTML代码。
请注意,JSONP请求必须以有效的JS脚本形式接收JSON。 它不适用于任何其他类型的输入。
出于安全原因,您不能从其他来源访问其他类型的资源,除非这些资源发送适当的Access-Control-Allow-Origin
HTTP标头。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.