1

How can I tell jQuery to automatically use "jsonp" for cross-domain ajax 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.

3
  • If you're going to write the code to handle JSONP anyway, what difference does it make? Via jQuery it's more-or-less transparent anyway; your callback gets called one way or the other. Commented Jun 3, 2011 at 13:20
  • Let's say I like to use "hacks" only when necessary. And JSONP is a hack necessary until CORS is supported by all major browsers. Commented Jun 3, 2011 at 13:27
  • A slight hack would be if you where going to use a standard method in a JavaScript library. You could check the current url and target url. Not ideal but fairly simple. Commented Jun 3, 2011 at 13:28

1 Answer 1

2

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
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.