我正在尝试在vanilla 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(未找到)
有没有人知道如何在vanilla js中使用https进行AJAX帖子请求?
答案 0 :(得分:0)
请尝试以下操作:
$(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 );
});