开发者

Access-Control-Allow-Origin Error Trying to GET json

I'm trying to utilize the Bing API to pull back spelling suggestions, but keep getting the below error:

XMLHttpRequest cannot load http://api.search.live.net/json.aspx?Appid=myIdWasHere&query=e开发者_如何学运维xplotion&sources=spell. Origin http://myWebServerNameWasHere is not allowed by Access-Control-Allow-Origin

I read a couple posts that looked similar, then about CORS, but I'm still a bit fuzzy. What do I have wrong in the below code?

$.ajax({
  type: 'GET',
  url: 'http://api.search.live.net/json.aspx',
  dataType: 'json',
  data: {
        Appid: '<myIdWasHere>',
        query: 'explotion',
        sources: 'spell'
        },
  beforeSend: function(xhr){
         xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
    }, 
  success: function(data) {    
    alert(data);
    },
  error: function(msg) {    
    alert(this.url + " -Failed"));
  }
});  


CORS (http://www.w3.org/TR/cors/) is a newish way of making cross-domain requests using XmlHttpRequest. Since you are making a request from your domain to api.search.live.net, it is considered a cross-domain request. CORS requires server-side support in order to work; specifically, Bing needs to include a special header that indicates that cross-domain requests are allowed.

My guess is that the Bing API does not allow cross-domain requests. In order to make a request, you should instead look into using JSON-P (http://en.wikipedia.org/wiki/JSON#JSONP). From their documentation, it looks like Bing does support JSON-P. Check out the "Callback Enumeration Example" section here:

http://msdn.microsoft.com/en-us/library/dd250846.aspx


Old post, but the Access-Control-Allow-Origin should be on the server not the client/calling domain.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜