[英]Ajax POST request on https in vanilla js
我正在嘗試在普通js中發出Ajax POST請求(該站點沒有jquery)。 我已經嘗試做這樣的事情,但是無法使其正常工作。
var params = { name: "Test"};
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://www.testurl.com/api/test/save', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
response = JSON.parse(xhr.responseText);
console.log(reponse);
}
};
xhr.send(JSON.stringify(params));
我收到此錯誤GET https://www.testurl.com/login.aspx?ReturnUrl=%2fapi%2ftest%2fsave 404(未找到)
有誰知道如何在香草js中使AJAX發布請求與https一起使用?
嘗試以下操作:
$(function () {
// event handler
function reqListener () {
console.log( this.response );
}
// get new XHR object
var newXHR = new XMLHttpRequest();
// bind our event listener to the "load" event.
// "load" is fired when the response to our request is completed and without error.
newXHR.addEventListener( 'load', reqListener );
// go to http://requestb.in/1k6rql51?inspect to view your request!
newXHR.open( 'POST', 'http://requestb.in/1k6rql51' );
// ^-- IMPORTANT: to send data to the server with it appearing in the url use 'POST'
// the object below can be crafted in any fashion. In the end you want an Object Literal with your data stored on it.
var jsonData = { name: 'Ray', password: 'NIGERA RULES?!' };
// HTTP Protocol can only work with strings when transmitting data over the internet.
// JSON is a class and .stringify is a class-method. We use it to format
// the Javascript Data, which lives in memory, to JSON string.
var formattedJsonData = JSON.stringify( jsonData );
// INSPECT WHAT YOU EXPECT, compare the two.
console.log( jsonData );
console.log( JSON.parse( formattedJsonData ) );
// send it off
newXHR.send( formattedJsonData );
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.