我正在尝试通过将数据提取到网页中来使用 Beanstalk (beanstalkapp.com) API,以便人们无需访问我的 SVN 即可查看它。
我尝试访问它的方法是通过 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>
如果我直接通过浏览器 ( http://username.beanstalkapp.com/api/changesets.json ) 访问 URL,它工作正常并返回 json。但是,我无法让 AJAX 返回它。任何帮助表示赞赏。谢谢!
最佳答案
您需要为跨域ajax 请求做代理。
通常的场景是这样的:
- 客户端向服务器发送ajax请求
- 您的服务器将请求转发到外部/远程服务器
- 等待远程服务器的响应
- 解析并处理来自远程服务器的响应
- 将响应发送回客户端
如果您使用的是 php,则可以使用 curl 发送请求,这很容易实现。我最近写了一篇关于这个话题的文章http://www.svlada.com/proxy-ajax-requests-curl-and-symfony-2/ .
关于javascript - 具有基本身份验证的 jQuery AJAX 跨域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11946307/