2013-03-27 63 views
0

我试图用剪切的API(http://clipped.me/api.html),返回JSON,但我遇到了一些麻烦。我使用的getJSON,并在Chrome的JS控制台我得到这些错误信息:

Resource interpreted as Script but transferred with MIME type text/html: " http://clipped.me/algorithm/clippedapi.php?url=callback=jQuery1910859611126 …emo-day-2013-still-looking-for-the-next-airbnb-or-dropbox/&_=1364420105379".

Uncaught SyntaxError: Unexpected identifier

Request Failed: parsererror, Error: jQuery19108596111265942454_1364420105378 was not called

这是我的JS:

var clippedAPI = "http://clipped.me/algorithm/clippedapi.php?url=[URL]callback=?"; 
    $.getJSON(clippedAPI, "http://pandodaily.com/2013/03/26/y-combinator-demo-day-2013-still-looking-for-the-next-airbnb-or-dropbox/").done(function(json) { 
      console.log("JSON Data: " + json.title); 
    }).fail(function(jqxhr, textStatus, error){ 
      var err = textStatus + ', ' + error; 
      console.log("Request Failed: " + err); 
    }); 

这是我第一次尝试做一些与API或JSON在所有,所以我真的不知道在这里做什么。我试过Google搜索,但找不到任何东西。我实际发送的数据正在被此jQuery通知切断,当我添加回调=时出现?

+0

您需要使用JSONP进行跨域请求。我建议使用'.ajax()'而不是像'$ .getJSON'这样的快捷方法,因为你将对你正在尝试做什么有更深的理解。文档:http://api.jquery.com/jQuery.ajax/ – Jasper 2013-03-27 21:44:42

+0

@Jasper:如果'callback'位于URL中,'$ .getJSON'会产生一个JSONP请求。 – 2013-03-27 21:47:37

+0

如果您尝试使用JSONP进行跨域请求,并且端点不支持JSONP(或CORS),那么您运气不好。 – 2013-03-27 21:48:13

回答

2

您的参数不会简单地“猜测”[URL]参数是什么。试试这个:

var clippedAPI = "http://clipped.me/algorithm/clippedapi.php"; 
$.ajax({ 
url: clippedAPI, 
type: "GET", 
dataType: "JSONP", 
data: { 
url: "http://pandodaily.com/2013/03/26/y-combinator-demo-day-2013-still-looking-for- the-next-airbnb-or-dropbox/"} 
}).done(function(json) { 
     console.log("JSON Data: " + json.title); 
}).fail(function(jqxhr, textStatus, error){ 
     var err = textStatus + ', ' + error; 
     console.log("Request Failed: " + err); 
}); 

即使这样但是失败,因为你的API端点似乎并不明白/支持JSONP和不提供Access-Control-Allow-Origin头。因此,你有两个选择:

  • 您可以反向代理本地API,以绕过跨域问题,经过标准的JSON
  • 你可以... ... EHM获得更好的API?与开发人员签一张门票以便将其分类。
+0

本地托管代理通常很容易实现。让JS调用本地托管的服务器端脚本,并让该脚本进行API调用,并将API的响应返回给JS。 – Jasper 2013-03-27 21:54:03

+0

谢谢,这是我的想法。 – 2013-03-27 21:55:27

+0

如果你使用的是Apache,mod_proxy允许你反向代理它。如果你使用nginx,甚至更好,proxy_pass字面上可以做到这一点!假设模块可用,两者都非常容易实现。 – 2013-03-27 21:56:57