jQuery AJAX Cross Domain with BASIC Authentication

2019-02-18 18:29发布

I'm attempting to make use of the Beanstalk (beanstalkapp.com) API by pulling data into a webpage so people can view it without accessing my SVN.

What I'm doing to try and access it is by using an AJAX request through jQuery. The code is below, but I get an error each time, and can't return the data.

<script type="text/javascript">
$(document).ready(function() {
    var tok = 'username' + ':' + 'password123';
        hash = btoa(tok);
        authInfo = "Basic " + hash;
    $.ajax({
        url: "http://username.beanstalkapp.com/api/changesets.json",
        beforeSend: function (xhr) { xhr.setRequestHeader ("Authorization", authInfo); },
        type: "GET",
        async: false,
        crossDomain: true,
        dataType: "json",
        success:  function(html){
            console.log(html);
        },
        error: function(html){
            console.log('error');
        }
    });
});
</script>

If I access the URL straight through my browser (http://username.beanstalkapp.com/api/changesets.json) it works just fine and returns the json. However, I cannot get the AJAX to return it. Any help is appreciated. Thanks!

3条回答
beautiful°
2楼-- · 2019-02-18 18:54

you cant get a json from other domain than yours. this is a security issue called same origin policy to get over it use JSONP not JSON.

查看更多
仙女界的扛把子
3楼-- · 2019-02-18 18:58

Check this jsfiddle. The username and password is incorrect. Give the correct username and password and check it once again.

查看更多
爷的心禁止访问
4楼-- · 2019-02-18 19:04

You will need to make proxy for cross-domain ajax requests.

Usual scenario looks like this:

  1. Client send ajax request to server
  2. Your server forwards request to external/remote server
  3. Waiting on response from remote server
  4. Parse and process response from remote server
  5. Send response back to client

If you are using php you can send requests with curl, and it is pretty easy to implement. I have wrote article on this topic recently http://www.svlada.com/proxy-ajax-requests-curl-and-symfony-2/.

查看更多
登录 后发表回答