通过jQuery获取JSONP

更新1:

如果我输入,这就是我在浏览器中获得的内容

http://www.remote_host.com/feed.php?callback=jsonpCallBack

{ "rss": { "channels": [ { "title": "title goes here", "link": "http://www.remote_server.com/feed.php", "description": "description goes here", "items": [ { "title": "item title goes here", "link": "item link goes here", "pubDate": "item date goes here", "description": "item description goes here" }, { "title": "item title goes here", "link": "item link goes here", "pubDate": "item date goes here", "description": "item description goes here" }, { "title": "item title goes here", "link": "item link goes here", "pubDate": "item date goes here", "description": "item description goes here" } ] } ] } } 

那么这不是jsonp吗?

原始问题:

我有以下脚本,我试图从远程主机获取json数据:

 $(document).ready(function() { get_json_feed(); function get_json_feed() { $.ajax({ url: 'http://www.remote_host.com/feed.php?type=json', type: 'GET', dataType: 'jsonp', error: function(xhr, status, error) { alert("error"); }, success: function(json) { alert("success"); } }); } }); 

但由于某种原因,我收到错误并警告:

警告:资源被解释为脚本,但使用MIME类型text / html进行传输。

错误:未捕获的SyntaxError:意外的令牌:

我究竟做错了什么?

JSONP“协议”依赖于站点使用表单的JavaScript语句回复您的请求,

  someFunction( someJSON ) 

函数的名称作为代码中的参数提供,其想法是响应脚本一旦被浏览器使用和解释,将导致使用已解析的JSON blob调用该函数 – 也就是说,一个JavaScript对象。 jQuery库将为您完成一些bookeeping工作,甚至可以创建要调用的全局范围函数(这将是仅调用您提供的回调作为“success”参数的代码)。

因此,您应该检查该服务器的实际响应是什么样的。 听起来好像它可能不是准备以这种方式响应的服务器。 您可能需要确保URL上有一个额外的参数,forms为“callback =?”。

我不确切地知道您面临的错误,但是在这里使用jsonp有一些有用的提示

  • error :不会为跨域脚本和JSONP请求调用此处理程序。
  • jsonp: 'callback', jsonpCallback: 'jsonpCallback'参数中写jsonp: 'callback', jsonpCallback: 'jsonpCallback' 。 将jsonp设置为callback然后将jsonpCallback设置为jsonpCallback使得查询字符串看起来像这样:

    http://domain.com/jsonp-demo.php?callback=jsonpCallback&name=watever

  • 使用JSONP加载JSON块。 会添加一个额外的?callback=? 到URL的末尾以指定回调。

您的完整脚本如下所示:

  

这里的例子

看起来服务器返回错误的Content-type标头。