开发者

using JSONP with AJAX

开发者 https://www.devze.com 2023-03-23 04:28 出处:网络
I have a page where i am using the wikipedia api. But since i cannot use JSON for cross domain restrictions i use JSONP. Now i can use the api if i query like

I have a page where i am using the wikipedia api. But since i cannot use JSON for cross domain restrictions i use JSONP. Now i can use the api if i query like

<script type="text/javascript">
function res(data){
  alert(data);
};
</script>
<script type="text/javascript" src="http://en.wikipedia.org/w/api.php?action=opensearch&search=api&callback=res&limit=10&namespace=0&format=json">
</script>

but i want to use this using AJAX. How can i do this? So开发者_JAVA百科me people suggested that i use jQuery but can somebody explain how do i do it in plain javascript?

Is in't there some way that i can use JSONP with asynchronous XHR calls?

Creating and then removing the script element is something i want to avoid.


JSONP calls are not asynchronous in nature since they use script tags. YOu can defer their execution by appending those tags later programmatically like this:

sendJsonpRequest = function (url, callback) {
    if (!(url && callback)) { return; }

    // create script element
    var script = document.createElement("script"),
        jsonpCallback = "jsonp_" + new Date(),
        done = false;

    url = url.replace(/\&$/, "") + "&callback=" + jsonpCallback;

    window[jsonpCallback] = function (args) {
        callback(args);

        // Garbage collect
        window[jsonpCallback] = undefined;
        try { delete window[jsonpCallback]; } catch (e) { }
        if (head) { head.removeChild(script); }
    };

    script.src = url;
    head.appendChild(script);
};


Plain Javascript JSONP library: http://blog.eood.cn/jsonp-library-in-plain-javascript-with-timeout

0

精彩评论

暂无评论...
验证码 换一张
取 消