【问题标题】:How can I get jsonp to play nice with my class?我怎样才能让 jsonp 与我的班级相处得很好?
【发布时间】:2023-03-18 08:11:01
【问题描述】:

整个 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 实例?

我真的被困在这里了。

【问题讨论】:

    标签: ajax jsonp


    【解决方案1】:

    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 参数。如果您使用的是第 3 方 API,他们已经支持此功能。希望这会有所帮助!

    【讨论】:

    • 您可能应该将随机值作为函数名称进行四舍五入/地板/天花板,其中不应包含 .
    • 很好,我还应该注意,我不建议使用我的函数名称随机化方法。可能类似于: var funcName = "data_" + (+new Date()) + Math.floor(Math.random()*100);会更合适。
    • 太棒了!非常感谢!
    猜你喜欢
    • 2010-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-08
    • 2017-05-20
    • 1970-01-01
    相关资源
    最近更新 更多