javascript 带有基本身份验证的 jQuery AJAX 跨域
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11946307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery AJAX Cross Domain with BASIC Authentication
提问by xxdrivenxx
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.
我试图通过将数据拉入网页来使用 Beanstalk (beanstalkapp.com) API,以便人们可以在不访问我的 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.
我正在做的尝试和访问它是通过 jQuery 使用 AJAX 请求。代码如下,但是每次都报错,无法返回数据。
<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!
如果我直接通过浏览器(http://username.beanstalkapp.com/api/changesets.json)访问 URL,它就可以正常工作并返回 json。但是,我无法让 AJAX 返回它。任何帮助表示赞赏。谢谢!
回答by svlada
You will need to make proxy for cross-domain ajax requests.
您将需要为跨域 ajax 请求制作代理。
Usual scenario looks like this:
通常的场景是这样的:
- Client send ajax request to server
- Your server forwards request to external/remote server
- Waiting on response from remote server
- Parse and process response from remote server
- Send response back to client
- 客户端向服务器发送ajax请求
- 您的服务器将请求转发到外部/远程服务器
- 等待来自远程服务器的响应
- 解析和处理来自远程服务器的响应
- 将响应发送回客户端
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/.
如果您使用的是 php,则可以使用 curl 发送请求,而且很容易实现。我最近写了关于这个主题的文章http://www.svlada.com/proxy-ajax-requests-curl-and-symfony-2/。
回答by zizoujab
you cant get a json from other domain than yours. this is a security issue called same origin policyto get over it use JSONPnot JSON.