Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
520 views
in Technique[技术] by (71.8m points)

ajax - Accessing web Service from jQuery - cross domain

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...