Is it Possible to Make Cross-Domain Requests in Javascript AND Set Custom Headers?

后端 未结 3 1447
借酒劲吻你
借酒劲吻你 2020-12-30 15:39

Since you can\'t apply custom headers on JSONP calls, how do I make cross domain requests AND apply custom headers using jQuery?

I\'m basically trying to access goog

3条回答
  •  鱼传尺愫
    2020-12-30 15:55

    You can use Google's JavaScript client library to query the Docs API. Although it doesn't come with helpers for Docs specifically, it can still be used with most APIs, including Docs. See this blog post by a Google employee that shows a working example.

    If you end up in an infinite loop of authorizations, see this related question from Google groups. Basically, the cookies aren't getting set fast enough, so when the JavaScript client library checks, it finds nothing and redirects to the OAuth authorization page. A solution is to either add a small delay before the check is done, or use a login button that initiates the authorization instead of doing it on page load.

    You would also need to add any image to your page that resides on the same domain. It can be hidden with CSS, as long as in the DOM.

    Using the example in the above blog post, I was able to retrieve my documents list with JavaScript alone. Here's the modified initialize function I used to get rid of the infinite 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 = $("");
            loginButton.click(function() {
                var token = google.accounts.user.login(scope); // can ignore returned token  
            });
            $("body").append(loginButton);
        }
    };  
    ​
    

提交回复
热议问题