Reputation: 11006
I am trying to acess a wcf service from a jQuery client
Specifically this example http://www.codeproject.com/KB/aspnet/WCF_JQUERY_ASMX.aspx#4
All works well when the client webpage is on the same domain as the service
As soon as I move the client webpage to another domain it breaks. It cant reach the service and the request fails
This happens for all the examples, ASMX, REST and WCF
any ideas how to get this working cross daomain?
Upvotes: 18
Views: 23613
Reputation: 39
I faced the same problem during 2 days and I found the solution, and it's elegant after googling a lot. I needed xss Ajax for some widget clients which pull datastream from tiers websites to my Rails app. here's how I did.
Upvotes: 0
Reputation: 3389
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);
}
Upvotes: 10
Reputation: 38238
Typically, you won't be able to; modern browsers restrict this to prevent cross-site scripting attacks. One way around it may be to use "padded" JSON, JSONP, which inserts the results in a script element on your page. There's a Microsoft WCF sample here which seems to do that.
Upvotes: 0
Reputation: 344497
You might want to check out JSONP (JSON with Padding). In short, it involves adding a script element to the page with the web service url as the src. The web service then wraps the JSON as the first argument in a callback function, which is executed when the script is parsed.
Script elements are exempt from the Same Origin Policy, which is how they are able to get around this issue..
Upvotes: 1