在JS中异步发布请求



你好,我设法通过ajax发送了一个post请求,但我想让它异步化,以防我的php文件需要更长的时间来处理。我似乎无法理解异步ajax部分的方法。到目前为止,这是我的功能:

submitForm(e) {
console.log(e);
e.preventDefault();
/* to prevent double submitting the form after the first submit*/
/* submitBtn.disbabled = true; */
this.isDisabled=true;
this.submitStatus = 'Successfully send!';

/* append form-values to the formdata s i can push it to my .php file */
const formData = new FormData();
formData.append('user_name', this.user_name);
formData.append('user_email', this.user_email);
formData.append('user_message', this.user_message);
/* async function should probably start here..*/

/* object of my http request */
const ajax = new XMLHttpRequest();
/* opneing my connection */
ajax.open('POST', this.url);
ajax.onreadystatechange = function() {
/* if state is send and status is ok */
if(ajax.readyState === 4 && ajax.status === 200) {
if (ajax.responseText === "success") {
/*  contactForm.innerHTML = `<h2>Thank you, ${contactName}, your message has been send.</h2>` */
}else {
this.submitStatus = ajax.responseText;
this.isDisbabled = false;
}
}
}
/* function-call of my promise function */

/* send the request with the appended form data. 
executing the load event */
ajax.send(formData);
/* resetting the input-fields to blank after the submit is done. */
this.user_name="";
this.user_email="";
this.user_message="";
}

我很感激你的帮助!

您可以始终将AJAX调用封装在异步函数中,如下所示:

async function ajaxRequest() {
//ajax call here (pass in anything you need)
return result;
}

然后在您的主要功能中等待结果:

let ajaxResult = await ajaxRequest();

因此,在ajax调用完成并收到结果之前,您的其余代码不会执行:(

最新更新