开发者

Automatic usage of jsonp for cross domain ajax requests

开发者 https://www.devze.com 2023-03-10 00:44 出处:网络
How can I tell jQuery to automatically use \"jsonp\" for cross-domain aja开发者_JS百科x requests while it keeps using \"json\" for same-domain requests? I want to write a client library in javascript

How can I tell jQuery to automatically use "jsonp" for cross-domain aja开发者_JS百科x requests while it keeps using "json" for same-domain requests? I want to write a client library in javascript which uses jsonp only when necessary. Let's take this small snippet as an example:

jQuery.ajax(url, {
    dataType: "jsonp"
});

When data type is "jsonp" then jquery always uses jsonp but already automatically detects if it can send a normal Ajax request (for same-domain requests) or if it has to use javascript injection (for cross-domain request).

So it seems jQuery is already able to auto-detect this and decides which technique to use. But it is not necessary to use jsonp when a standard Ajax request is possible so I want to use "jsonp" only for cross-domain requests. How can I do this?

Or maybe it is possible to ask jQuery if a url is cross-domain or not? Then I could check this myself and call jQuery.ajax with different data types.


You could use something like this and then check that the scheme/hostname match. One easy alternative to parse an url is to create an a element and have the browser give you the url parts.

function sameOrigin(url){
    var link = document.createElement("a");
    link.href = url;

    return ((link.protocol + link.host) === window.location.protocol + window.location.host);
}


    var url = "http://stackoverflow.com/questions/6227584/jquery-automatic-usage-of-jsonp-for-cross-domain-ajax-requests";
    if (sameOrigin(url)){
     // use json
    }else{
     // use jsonp
    }
0

精彩评论

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