Reputation: 935
This Python code works fine
print 'foo'
params = {'memberId': '1'}
data = urllib.urlencode(params)
url = 'http://aaa.bbb.com/ccc/'
req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
f = urllib2.urlopen(req)
response = f.read()
print '===>', response
response = eval(response.decode('unicode-escape'))
f.close()
I am wondering what's the corresponding javascript code for this? I tried this, alerted "error". Currently I am on ddd.bbb.com. The web service is on aaa.bbb.com. I cannot set relative path for this.
Please advise on how to configure cross-domain. Thanks.
jQuery.ajax({
url: 'http://aaa.bbb.com/ccc',
type: 'GET',
contentType: "application/json",
dataType: "json",
data: {'memberId':'1'},
success: function (data) {
alert("ok");
},
error: function () {
alert("error");
}
});
Upvotes: 0
Views: 1272
Reputation: 35770
There are approximately one gajillion (that's my technical estimate ;-) ) other Stack Overflow questions about Javascript's "same origin policy", and how you can work around it. I strongly recommend checking them out.
As a quick summary, your basic options are:
And just so you understand the core problem, the gist of it is that browsers don't let code from evildomain.com access yourbank.com, as a security precaution. However, browsers will let you retrieve scripts from yourbank.com, no matter what your origin is, so you can exploit that using something called JSONP ... but for JSONP to work, the owner of yourbank.com has to support it (they have to tailor their scripts for you).
Browsers will also let you access yourbank.com if yourbank.com explicitly says "it's cool if evildomain.com messes with us". They do that by putting a special file in a special place on their site (I forget the details, but they're easy to look up).
If you can't do either of those, you can just get your evildomain.com server to go to yourbank.com for you. Servers aren't bound by the same restrictions as browsers, so they can visit any site they want. When it does, it can send you back the content it finds there, and this is known as a "proxy" (to yourbank.com through evildomain.com, which is the end doing the proxying).
Hopefully that clarifies matters a bit.
Upvotes: 1