简体   繁体   English

在 JS 中异步一个 Post-Request

[英]Async a Post-Request in JS

Hello I managed to get my submit to send a post request via ajax, but I want to make this asynchronous in case my php-file takes longer to process.您好,我设法让我的提交以通过 ajax 发送发布请求,但我想让它异步,以防我的 php 文件需要更长的时间来处理。 I can't seem to wrap my head around the way to async the ajax part.我似乎无法理解异步 ajax 部分的方法。 Here is my function so far:到目前为止,这是我的功能:

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="";
    }

I appreciate the help!我感谢您的帮助!

You could always wrap the AJAX call in an async function like so:您始终可以将 AJAX 调用包装在一个异步函数中,如下所示:

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

and then in your main function just await the result:然后在你的主函数中等待结果:

let ajaxResult = await ajaxRequest();

so the rest of your code won't execute until the ajax call has finished and the result has been received :)因此,在 ajax 调用完成并收到结果之前,您的其余代码不会执行:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM