我怎样才能让jsonp与我的班级相处得很好?

时间:2010-05-30 02:22:40

标签: ajax jsonp

整个jsonp的事情让人很困惑......

这是我想要做的:

  • 我有一个班级DataRetriever
  • 该类有一个方法GetData
  • GetData使用以下代码发出jsonp请求:

    var new_tag = document.createElement('script');
    new_tag.type = 'text/javascript';
    new_tag.src = 'http://somesite.com/somemethod?somedata';
    // Add the element
    var bodyRef = document.getElementsByTagName("body").item(0);
    bodyRef.appendChild(new_tag);
    

现在,来自服务器somesite.com的jsonp数据可以使用数据调用我的代码中的函数。问题是,如何将数据传递给请求它的DataRetriever实例?

我真的被困在这里。

1 个答案:

答案 0 :(得分:4)

jQuery提出的解决方案是提供一个匿名的回调函数:

jQuery.getJSON("http://mycrossdomain.com/?callback=?", function(data) {
   // Now I have the data
});

我认为这也可以适应你的情况。

var data = new DataRetriever();
data.GetData(function(data) {
    // Now I have the data 
});

如果你不想提供匿名函数,你可以在GetData函数的幕后做同样的事情。

function GetData(callback) { // optional
    // Create random function name however you want
    var funcName = "data_" + (+new Date() + Math.floor(Math.random()*100)),
        // Moved this up to be available in the random function
        new_tag = document.createElement('script');
    // This part will allow you to do the callback behind the scenes if callback isn't provided as a param
    callback = callback || function(data) {
        this.dataReturned = data; // or something
    }
    // Assign it to the window object
    window[funcName] = function(data) {
         callback(data);
         // Unassign this function
         delete window[funcName];
         // Recycle the script tag
         document.body.removeChild(new_tag);
    }
    new_tag.type = 'text/javascript';
    new_tag.src = 'http://somesite.com/somemethod?callback='+funcName;
    // Add the element
    document.body.appendChild(new_tag);
 }

请注意,您必须确保JSONP请求接受回调GET参数。如果您使用的是第三方API,则他们已经支持此功能。希望这有帮助!

相关问题