3

我正在尝试将jQuery AJAX请求转换为一些基本的http身份验证网址。 这里是我的jQuery代码:jQuery ajax基本身份验证不起作用

jQuery.ajax({ 
    url: "https://abc.com/houses/1/appliance_hints", 
    method: 'GET', 
    cache: false, 
    crossDomain: true, 
    beforeSend: function(xhr){ 
    xhr.setRequestHeader('Authorization', 'Basic Z3NsYWI6cGFzczFnczFhYg=='); 
    }, 
    success: function(result){ 
    alert(result); 
    } 
}); 

我设置请求头“授权”在这里。但这里是我在FF中请求标题中看到的内容

Host <host> 
User-Agent Mozilla/5.0 (Ubuntu; X11; Linux x86_64; rv:8.0) Gecko/20100101 Firefox/8.0 
Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 
Accept-Language en-us,en;q=0.5 
Accept-Encoding gzip, deflate 
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7 
Connection keep-alive 
Origin <origin> 
Access-Control-Request-Me... GET 
Access-Control-Request-He... authorization,x-requested-with 

我做错了什么? 我收到了响应中的状态码302。 是否有任何服务器端配置错误?

回答

3

我注意到你已经给你添加了crossDomain: true$.ajax调用,所以我认为你试图从远程域获取某些东西?

无论如何,您遇到的主要问题是您违反了Same origin policy

如果您可以控制remote_url(在您的示例中为abc.com),您可以将其设置为发送某个标头以允许这些呼叫。

例如:

Access-Control-Allow-Origin: http://permitted_domain.com 

PHP例子:

header('Access-Control-Allow-Origin: http://permitted_domain.com'); 
// or to allow all 
header('Access-Control-Allow-Origin: *'); 
0
var settings = { 
    "async": true, 
    "crossDomain": true, 
    "url": "YOUGETURL", 
    "method": "GET", 
    "headers": { 
    "authorization": "Basic Z3NsYWI6cGFzczFnczFhYg==", 
    "cache-control": "no-cache" 

    } 
} 

$.ajax(settings).done(function (response) { 
    console.log(response); 
});