gpt4 book ai didi

javascript - 我将如何在 Vanilla JS 中执行此 ajax jquery?

转载 作者:行者123 更新时间:2023-12-05 08:22:09 25 4
gpt4 key购买 nike

我正在尝试用 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 请求?

最佳答案

你应该使用 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.');
});

fetch 返回一个 promise,并处理响应中的文本,如果您想使用更自动化的东西,请尝试 Axios。

关于javascript - 我将如何在 Vanilla JS 中执行此 ajax jquery?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64612746/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com