Is it possible to allow cross-domain requests in Javascript and set custom headers?

Since you cannot apply custom headers to JSONP calls , how do I make cross-domain requests and apply custom headers using jQuery?

I am basically trying to access google docs with jQuery and should pass an authentication token:

var token = "my-auth-token"; $.ajax({ url: "http://docs.google.com/feeds/documents/private/full?max-results=1&alt=json", dataType: 'json', beforeSend: function(xhr) { xhr.setRequestHeader("Authorization", "GoogleLogin auth=" + token); }, success: function(data, textStatus, XMLHttpRequest) { }, error: function(XMLHttpRequest, textStatus, errorThrown) { } }); 

Note. The purpose of this is to completely bypass the application layer. Simple use of ruby ​​to connect to the Google data API, but it requires a lot of resources that process feeds all the time on the server side.

+5
javascript jquery ajax cross-domain
Jun 18 '10 at 22:01
source share
3 answers

You can use the JavaScript JavaScript client library to request the Docs API. Although it does not come with helpers for Docs specifically, it can still be used with most APIs, including Docs. See this blog post by a Google employee for a working example.

If you end an endless authorization cycle, see this related question from Google groups. Basically, cookies are not set quickly enough, so when the JavaScript client library checks, it finds nothing and redirects to the OAuth authorization page. The solution is to either add a small delay before the check is completed, or use the login button, which initiates authorization instead of doing this when the page loads.

You will also need to add any image to your page located in the same domain. It can be hidden using CSS if in the DOM.

Using the example in the blog above, I was able to get a list of my documents using JavaScript only. Here's the modified initialization function that I used to get rid of the endless authorization loop:

 function initialize() { var scope = 'http://docs.google.com/feeds/'; if (google.accounts.user.checkLogin(scope)) { var service = new google.gdata.client.GoogleService('writely', 'DocList-App-v1.0'); service.getFeed(scope + 'documents/private/full/', handleFeed, handleError); } else { var loginButton = $("<button>Click here to login</button>"); loginButton.click(function() { var token = google.accounts.user.login(scope); // can ignore returned token }); $("body").append(loginButton); } };​ 
+5
Jun 18 '10 at 23:09
source share

Consider writing server-side code that plays proxies and let jQuery call it.

+3
Jun 18 '10 at 22:24
source share

You can, if the external domain allows this by sending the appropriate Access-Control-Allow-Origin header. Then simply use the XMLHttpRequest API in browsers that support the standard cross-domain XHR API and XDomainRequest in IE.

0
Jun 19 '10 at 1:07
source share



All Articles