【问题标题】:What's the best way to get JSON-P data without jQuery?在没有 jQuery 的情况下获取 JSON-P 数据的最佳方法是什么?
【发布时间】:2012-03-22 23:58:50
【问题描述】:

我有一个将返回 JSON-P 数据的应用程序,我一直在使用 jQuery 的简单 getJSON 方法与它进行通信:

$.getJSON("http://somedomain.com/&callback=?", this.callback);

我将我的代码捆绑到一个库中,我喜欢不需要 jQuery。重写 getJSON 函数,让我可以得到跨域的 JSON-P 数据有多容易?

【问题讨论】:

    标签: javascript ajax jsonp


    【解决方案1】:

    可以做类似的事情

    <script>
    function mycallback(data) {
       //do something funky with 'data'
    }
    
    var oHead = document.getElementsByTagName('HEAD').item(0);
    var oScript= document.createElement("script");
    oScript.type = "text/javascript";
    oScript.src="http://somedomain.com/&callback=mycallback";
    oHead.appendChild( oScript);
    </script>
    

    【讨论】:

    • 每次调用它时我是否需要担心清除“陈旧”的脚本标签?我会每秒调用几次。
    • 并非如此。不。尽管确实要安排回调具有唯一的名称。否则,如果请求被快速连续触发,回调很容易被越过。这就是 jquery 通常处理创建回调的原因 - 所以它可以管理名称。
    • 我也意识到我可以添加类似 setTimeout(function() { oHead.removeChild(oScript); }, 1000);到代码的末尾。
    猜你喜欢
    • 2012-02-23
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-28
    • 1970-01-01
    • 2016-09-05
    • 2023-03-25
    相关资源
    最近更新 更多