开发者

How to make an ajax call to another domain?

I am trying to build an interface that communicates with a REST API for attask.com. Their API is convenient because it returns JSON. I thought that was perfect because I could forget about server-side C# code and just write the interface using jQuery and AJAX. However, when I try to make an AJAX request to their API I get an error in Chrome's javascript console:

Origin http://mysite.com is not allowed by Access-Control-Allow-Origin.

What does this mean? Is this the browser preventing the request? If so, wh开发者_如何学Goy?

Update:

If I don't have any control over the server and it does not respond to JSONP requests, is my only option to employ a server-side REST client and have my AJAX talk to my own domain instead of attempting to go cross-domain?


I found that jQuery-JSONP is the easiest way to do this.
jQuery JSONP is an alternative solution to jQuery's implementation of JSONP

jQuery-JSONP features:

  1. error recovery in case of network failure or ill-formed JSON responses,
  2. precise control over callback naming and how it is transmitted in the URL,
  3. multiple requests with the same callback name running concurrently,
  4. two caching mechanisms (browser-based and page based),
  5. the possibility to manually abort the request just like any other AJAX request,
  6. a timeout mechanism.

Sample Code to Get user profiles from YouTube

function getProfile(userId) {

    $.jsonp({
      "url": "http://gdata.youtube.com/feeds/api/users/"+userId+"?callback=?",
      "data": {
          "alt": "json-in-script"
      },
      "success": function(userProfile) {
          // handle user profile here 
      },
      "error": function(d,msg) {
          alert("Could not find user "+userId);
      }
    });
}

For more samples.


Alternatively, you can use the fututre standard Cross Origin Resource Sharing that is supported on modern browsers and fallback to JSONP for the other browsers.


You'll want to use JSONP, JQuery has nice support for this built in. See JQuery Documentation for more info.


You need to make a JSONP request to perform a cross domain AJAX request, you can do this by appending

callback=?

To the URL you send the request to

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜