Accessing web Service from jQuery – cross domain

You are running up against the Same-Origin Policy. The web service that you are accessing must reside on the same domain as the jQuery script that is making the request. This policy is enforced by all browsers to prevent – for example – cross-site scripting and code injection attacks on web applications.

There are various ways around it, including JSONP, Proxies or Flash.

We’ll need a little more information before we can suggest which technique you should use. I tend to favor JSONP. But in the meantime, here’s some light reading:

http://taossa.com/index.php/2007/02/08/same-origin-policy/

https://developer.mozilla.org/En/Same_origin_policy_for_JavaScript

Here’s an example use of JSONP:

url = "http://www.test.com/getData.php?callback=parseResults";

document.body.appendChild((function() {
    var newScript = document.createElement("script");
    newScript.type = "text/javascript";
    newScript.src = url;
    return newScript;
})());

function parseResults(data) {
    alert(data);
}

Leave a Comment