I have an api set up on another domain, domain B (api.domainb.com), and want to make a call to it from domain A (www.domaina.com). However, when I do a call from domain A to domain B via jquery ajax, jquery ends up trying to call www.dom开发者_StackOverflow社区aina.com/api.domainb.com which obviously will return an error. Here is the relevant javascript code
$.ajax(
url: 'http://api.domainb.com',
type: 'GET',
dataType: 'jsonp',
data: {hello: 'world'},
crossDomain: true,
success: function(data){
alert(JSON.stringify(data))
},
error: function(error){
alert(JSON.stringify(error))
});
Eventually, the code in domain A and domain B will be on the same domain, but for now, I need to make a cross-domain call. Any suggestions as to how to make this work?
You're just missing the protocol so that the Ajax call knows it's a different domain and not a relative URL. Try using url: 'http://api.domainb.com'
.
You cannot make cross-domain calls; browsers simply do not allow it in general. However, the reason you're seeing the behavior you describe is that your URL is missing the "http://" prefix.
There are some things you can do with fairly new HTML5 APIs to sort-of "get permission" to do cross-domain calls.
edit @Dan points out correctly that while XMLHttpRequest (what people usually call "ajax") won't do cross-domain stuff (CORS aside), it's possible to leverage the fact that <script>
tags can reference other domains in order to put together a service. The server-side code has to be different, however. (That's usually called "JSONP".)
精彩评论