簡體   English   中英

在 JS 中異步一個 Post-Request

[英]Async a Post-Request in JS

您好,我設法讓我的提交以通過 ajax 發送發布請求,但我想讓它異步,以防我的 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 調用完成並收到結果之前,您的其余代碼不會執行:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM