[英]jQuery cross domain POST shenanigans
我正在嘗試對API進行身份驗證,該API僅允許您使用帶有JSON的POST作為表單數據進行身份驗證,格式為{“username”:“myusername”,“password”:“mypassword”}。
我已經嘗試了兩天來使用jQuery,但是我遇到了問題,因為它是跨域的。 我怎么能做到這一點?
錯誤信息:
Request Method:OPTIONS
Status Code:405 METHOD NOT ALLOWED
代碼到現在為止:
var username = "myusername";
var password = "mypass"
var authurl = "https://myurl";
$.ajax
({
type: "POST",
url: authurl,
dataType: 'json',
contentType: "application/json; charset=utf-8",
async: false,
data: {'json':'{"username":"' + username + '", "password":"' + password + '"}'},
success: function (result) {
$('#json').html(result);
}
})
總結一下:
非常感謝您的幫助 :)
你應該遵循不同的模式。 您的本地JS將對本地URL執行ajax發布,該URL將接受帶有json數據的POST方法。
此時,您的服務器代碼將使用適當的數據向遠程服務器執行HTTP POST,獲取響應,並將其發送回調用的js。
問題是您嘗試POST的域不響應在每個跨域請求之前發送的OPTIONS請求。 使用OPTIONS請求,瀏覽器會收到有關跨域規則等的信息。要啟用跨域請求,服務器必須設置Access-Control-Allow-Origin:*
(或實際上是腳本的域,但*涵蓋所有內容)並且可能是Access-Control-Allow-Methods: GET, POST, OPTIONS
標題。
我在GoDaddy上有一個共享主機。 我也需要回答這個問題,在搜索之后我發現它是可能的。
我寫了一個.htaccess文件,把它放在與我的操作頁面相同的文件夾中。 以下是.htaccess文件的內容:
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
這是我的ajax電話:
$.ajax({
url: 'http://www.mydomain.com/myactionpagefolder/gbactionpage.php', //server script to process data
type: 'POST',
xhr: function() { // custom xhr
myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // for handling the progress of the upload
}
return myXhr;
},
//Ajax events
beforeSend: beforeSendHandler,
success: completeHandler,
error: errorHandler,
// Form data
data: formData,
//Options to tell JQuery not to process data or worry about content-type
cache: false,
contentType: false,
processData: false
});
請參閱此文章以供參考:
對於跨域的東西,使用JSONP (搜索crossDomain)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.