使用jQuery / Jsonp发送跨域请求和解析结果?

时间:2013-07-18 13:48:18

标签: ajax jquery jsonp

我正在尝试使用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 < 

那么如何以正确的方式制作呢?

1 个答案:

答案 0 :(得分:-2)

如果远程端没有为其JSONP输出设置正确的Content-Type标头,则第一个警告是正常的。这只是一个警告,它不会带来任何伤害。

如果第二个错误来自尝试访问stackoverflow网站,则该错误仅仅是因为您尝试在JS解释器处抛出HTML代码。

请注意,JSONP请求必须以有效的JS脚本的形式接收JSON。它不适用于任何其他类型的输入。

出于安全原因,您无法访问其他来源的其他类型的资源,除非这些资源发送相应的Access-Control-Allow-Origin HTTP标头。

相关问题