我想用Vanilla JS替换以下jquery Ajax请求
// Working jQuery
$.ajax({
url: "https://reqres.in/api/register",
type: "POST",
data: {
"email": "eve.holt@reqres.in",
"password": "pistol"
},
success: function(response){
console.log('jQuery success', response);
}
});
这是可以正常工作的Vanilla JS,
// Working VanillaJS
var xhr = new XMLHttpRequest();
xhr.open("POST", 'https://reqres.in/api/register', true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (this.readyState !== XMLHttpRequest.DONE) return
if (this.status === 200)
console.log('Vanilla JS success', this.responseText)
else
console.log('Vanilla JS fails', this.responseText)
}
xhr.send("email=eve.holt@reqres.in&password=pistol");
为了方便起见,我尝试使用FormData准备数据。但是,它不再起作用,似乎服务器未接收到数据:
// Non working VanillaJS with FormData
var formData= new FormData();
formData.append('email', 'eve.holt@reqres.in');
formData.append('password', 'pistol');
var xhr2 = new XMLHttpRequest();
xhr2.open("POST", 'https://reqres.in/api/register', true);
xhr2.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr2.onreadystatechange = function() {
if (this.readyState !== XMLHttpRequest.DONE) return
if (this.status === 200)
console.log('FormData success', this.responseText)
else
console.log('FormData fails', this.responseText)
}
xhr2.send(formData);
我被困了一段时间,欢迎您的帮助。
这是一个JSFiddle,上面有3个代码:https://jsfiddle.net/Imabot/0a8qg1fs/13/