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); 
});