2011-01-12 66 views
5

不应该使用JQuery工作跟踪AJAX请求?如何使用JSONP查询Facebook Graph API

$.getJSON('https://graph.facebook.com/138654562862101/feed?callback=onLoadJSONP'); 

我已经定义了一个名为onLoadJSONP一个回调函数。

而Chrome给我一个典型的同源-策略错误:

XMLHttpRequest cannot load https://graph.facebook.com/138654562862101/feed?callback=onLoadJSONP . Origin null is not allowed by Access-Control-Allow-Origin.

我想JSONP周围的工作,我究竟做错了什么?

回答

17

jQuery detects JSONP desired behavior专门callback=?,所以你需要正是的是,再传给你要处理它的功能。没有外界的变化,你可以这样做:

$.getJSON('https://graph.facebook.com/138654562862101/feed?callback=?', onLoadJSONP); 

这使得搜索callback=?仍然使用你的函数直接作为回调的工作。以前,并没有检测到你想要JSONP抓取,而是试图使用XMLHttpRequest获取数据......由于相同的源策略限制而失败。

+0

这是否也适用于IE? (这适用于Chrome和Firefox,但在IE中失败)。谢谢。 – user1055761

+0

你在IE中遇到什么错误? –

+0

当通过IE调试器进行调试时,它给了我'无运输'错误。你有这个工作在IE浏览器?谢谢 ! – user1055761

4

它必须是“callback =?”然后将回调定义为请求的最后一个参数。

$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", 
    { 
    tags: "cat", 
    tagmode: "any", 
    format: "json" 
    }, 
    function(data) { 
    $.each(data.items, function(i,item){ 
     $("<img/>").attr("src", item.media.m).appendTo("#images"); 
     if (i == 3) return false; 
    }); 
    }); 
1

下面的JavaScript代码,你做任何跨域AJAX调用之前简单的附加。

jQuery.support.cors = true; 

$.ajaxTransport("+*", function(options, originalOptions, jqXHR) { 

    if(jQuery.browser.msie && window.XDomainRequest) { 

    var xdr; 

    return { 

     send: function(headers, completeCallback) { 

      // Use Microsoft XDR 
      xdr = new XDomainRequest(); 

      xdr.open("get", options.url); 

      xdr.onload = function() { 

       if(this.contentType.match(/\/xml/)){ 

        var dom = new ActiveXObject("Microsoft.XMLDOM"); 
        dom.async = false; 
        dom.loadXML(this.responseText); 
        completeCallback(200, "success", [dom]); 

       }else{ 

        completeCallback(200, "success", [this.responseText]); 

       } 

      }; 

      xdr.ontimeout = function(){ 
       completeCallback(408, "error", ["The request timed out."]); 
      }; 

      xdr.onerror = function(){ 
       completeCallback(404, "error", ["The requested resource could not be found."]); 
      }; 

      xdr.send(); 
     }, 
     abort: function() { 
      if(xdr)xdr.abort(); 
     } 
    }; 
    } 
});