我如何在 vanilla JS 中执行此 ajax jquery?
How would I do this ajax jquery in vanilla JS?
我正在尝试用 Vanilla JS 编写此 jQuery ajax POST 请求;它最初是:
$.ajax({
method: 'POST',
url: window.location.href + 'email',
data: {
toEmail: to, //var set elsewhere
fromName: from, //var set elsewhere
message: message, //var set elsewhere
recaptcha: recaptcha //var set elsewhere
}
})
.done(function (data) {
handleResponse(data, form)
})
.fail(function (error) {
console.error(error)
alert('Couldn't send your email. Try again later.')
})
handleResponse 是
function handleResponse (data, form) {
if (!data.message) return
if (!form) return
const responseMessage = form.querySelector('[email-response]')
const formData = form.querySelector('[email-data]')
if ('success' === data.message) {
responseMessage.classList.remove('error')
responseMessage.classList.add('success')
responseMessage.innerText = 'Success! Email has been sent.'
formData.classList.add('hidden')
return
}
return handleError(responseMessage, data)
}
但是,我尝试将 Ajax 部分转换为:
var req = new XMLHttpRequest();
req.onLoad = function(e){
resolve(req.response);
}
req.onerror = function(e){
console.log(e);
alert('Couldn't send your email. Try again later.')
};
var data = {
toEmail: to, //var set elsewhere
fromName: from, //var set elsewhere
message: message, //var set elsewhere
recaptcha: recaptcha //var set elsewhere
}
}
var url = window.location.href + 'email';
req.open("POST",url,true);
req.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
req.send(data);
我收到一个控制台错误 req is not defined
我做错了什么?我怎样才能正确地在 vanilla JS 中执行 jQuery ajax 请求?
在 Vanilla js 中你可以使用 XMLHttpRequest
var http = new XMLHttpRequest();
var url = 'your url';
var params = 'orem=ipsum&name=binny';
http.open('POST', url, true);
//Send the proper header information along with the request
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
// http.responseText will be anything that the server return
alert(http.responseText);
}
}
http.send(params);
或者如果你传递了一个对象,你可以使用 FormData
var http = new XMLHttpRequest();
var url = 'your urk';
var myForm = new FormData()
myForm.append('foo', 'bar')
http.open('POST', url, true);
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
// http.responseText will be anything that the server return
alert(http.responseText);
}
}
http.send(myForm);
你应该使用 fetch API:
const url = `${window.location.href}email`;
const payload = {
toEmail: to, //var set elsewhere
fromName: from, //var set elsewhere
message: message, //var set elsewhere
recaptcha: recaptcha //var set elsewhere
};
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
})
.then((response) => {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
})
.then((response) => response.json())
.then((data) => {
handleResponse(data, form);
})
.catch((error) => {
console.error(error);
alert('Couldn't send your email. Try again later.');
});
获取 returns 承诺,并在响应中处理文本,如果您想使用更自动化的东西,请尝试 Axios。
我正在尝试用 Vanilla JS 编写此 jQuery ajax POST 请求;它最初是:
$.ajax({
method: 'POST',
url: window.location.href + 'email',
data: {
toEmail: to, //var set elsewhere
fromName: from, //var set elsewhere
message: message, //var set elsewhere
recaptcha: recaptcha //var set elsewhere
}
})
.done(function (data) {
handleResponse(data, form)
})
.fail(function (error) {
console.error(error)
alert('Couldn't send your email. Try again later.')
})
handleResponse 是
function handleResponse (data, form) {
if (!data.message) return
if (!form) return
const responseMessage = form.querySelector('[email-response]')
const formData = form.querySelector('[email-data]')
if ('success' === data.message) {
responseMessage.classList.remove('error')
responseMessage.classList.add('success')
responseMessage.innerText = 'Success! Email has been sent.'
formData.classList.add('hidden')
return
}
return handleError(responseMessage, data)
}
但是,我尝试将 Ajax 部分转换为:
var req = new XMLHttpRequest();
req.onLoad = function(e){
resolve(req.response);
}
req.onerror = function(e){
console.log(e);
alert('Couldn't send your email. Try again later.')
};
var data = {
toEmail: to, //var set elsewhere
fromName: from, //var set elsewhere
message: message, //var set elsewhere
recaptcha: recaptcha //var set elsewhere
}
}
var url = window.location.href + 'email';
req.open("POST",url,true);
req.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
req.send(data);
我收到一个控制台错误 req is not defined
我做错了什么?我怎样才能正确地在 vanilla JS 中执行 jQuery ajax 请求?
在 Vanilla js 中你可以使用 XMLHttpRequest
var http = new XMLHttpRequest();
var url = 'your url';
var params = 'orem=ipsum&name=binny';
http.open('POST', url, true);
//Send the proper header information along with the request
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
// http.responseText will be anything that the server return
alert(http.responseText);
}
}
http.send(params);
或者如果你传递了一个对象,你可以使用 FormData
var http = new XMLHttpRequest();
var url = 'your urk';
var myForm = new FormData()
myForm.append('foo', 'bar')
http.open('POST', url, true);
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
// http.responseText will be anything that the server return
alert(http.responseText);
}
}
http.send(myForm);
你应该使用 fetch API:
const url = `${window.location.href}email`;
const payload = {
toEmail: to, //var set elsewhere
fromName: from, //var set elsewhere
message: message, //var set elsewhere
recaptcha: recaptcha //var set elsewhere
};
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
})
.then((response) => {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
})
.then((response) => response.json())
.then((data) => {
handleResponse(data, form);
})
.catch((error) => {
console.error(error);
alert('Couldn't send your email. Try again later.');
});
获取 returns 承诺,并在响应中处理文本,如果您想使用更自动化的东西,请尝试 Axios。