javascript - Ajax Vanilla JS - ajax 异步继续,无需等待 readState 4,状态 200

标签 javascript php html ajax

TLDR:我想等待第一个请求完成,然后再继续执行第二个请求等。

<小时/>

你好,

我目前正在开发一个 HotSpot 页面。用户需要输入他的电子邮件,瞧!他可以访问互联网。

假设在后台发生的事情是,当用户插入他的电子邮件并按发送时;

  1. 使用用户名和密码向路由器发出 AJAX 异步 POST,

然后js/html页面等待来自路由器的readyState === 4 (DONE)响应,

  • 向不同网络上的服务器发出 AJAX 异步 POST(这需要用户具有互联网连接),该服务器向用户发送电子邮件,
  • 然后js/html页面等待DONE响应

  • 用户被重定向。
  • 这基本上就是应该发生的事情。实际发生的情况是,JS 不会等待readyState === 4 和Status === 200。一旦用户单击“提交”,他就会立即重定向。

    我无法使用 JQuery,因为路由器 (Mikrotik) 正在使用 $ 来达到其自身目的。

    使用 F12 工具检查网络后,我可以看到到路由器的 POST 状态为 200,并且携带正确的参数 (username=HSuser&password=SimpleUserPassword),并且我可以看到到服务器的 POST 有状态为 200,并且还具有正确的参数(电子邮件地址,即:Email=Ba%40loo.ns)。

    我猜我的 JS 代码有些错误,因为它不等待。

    此外,由于摆弄代码后的一些原因,没有更多电子邮件被插入到数据库中(之前是这样,不知道现在是什么问题。)

    以下是当前代码。我还会发布以前的版本(也不起作用),以防有人发现那里的问题。

    如果有人需要任何其他信息,请告诉我。

    谢谢。

    <小时/>

    编辑 3:

    我继续阅读 Stack Overflow,偶然发现了这个 piece of information ...

    The server is responsible for providing the status, while the user agent provides the readyState.

    这是服务器端自动完成的,还是我需要以某种方式实现它?

    <小时/>

    编辑 1.:

    我在这里尝试了控制台日志

                    if (xhr.readyState === DONE){
    
                        console.log("XHR1" + xhr.readyState);
                        console.log("XHR1" + xhr.status);
    
                        if (xhr.status === OK){
    

    这里

                                if (xhr2.readyState === DONE){
    
                                    console.log("XHR2" + xhr2.readyState);
                                    console.log("XHR2" + xhr2.status);
    
                                    if (xhr2.status === OK){    
    

    我只得到了XHR1(XHR14和XHR1200),我没有从XHR2得到任何东西。

    <小时/>

    编辑2.:

    尝试用 onload 替换 onreadystatechange,仍然做同样的事情。

    <小时/>

    当前 HTML 代码:

    <!DOCTYPE html>
    <html>
    <head>
    <meta content="text/html" />
    <meta charset="utf-8" />
    
    <title>HotSpot</title>
    
    </head>
    <body>
    
        <!-- Email form which is saved into the DB -->
        <form accept-charset="utf-8" name="mail" onsubmit="return false;" method="post" id="mail">
            <h1>Hotspot</h1>
            <h2>To gain internet access, enter your email.</h2>
            <br />
            <input type="text" id="email" name="email" autofocus="autofocus" />
            <br />
            <input type="submit" value="Submit" id="submit_ok" name="submit_ok" /> <br />
        </form>
    
    <script type="text/javascript">
    
    document.getElementById("submit_ok").addEventListener("click", SendAjax);
        function SendAjax() {
            var email = document.getElementById("email").value;
            console.log(email);
            // Check if fields are empty 
            if (email=="") {
                alert("Please enter your email.");
            }
            // AJAX code to submit form
            else{
                var xhr = new XMLHttpRequest();
                xhr.open('POST', 'http://router/login', true);
                xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded", "Access-Control-Allow-Origin: *");
    
                xhr.onreadystatechange = function () {
                    var DONE = 4;
                    var OK = 200;
                    if (xhr.readyState === DONE){
                        if (xhr.status === OK){
                            var xhr2 = new XMLHttpRequest();
                            xhr2.open('POST', 'http://server/insertDB.php', true);
                            xhr2.setRequestHeader("Content-type", "application/x-www-form-urlencoded", "Access-Control-Allow-Origin: *");
                            var useremail = document.getElementById("email").value;
    
                            xhr2.onreadystatechange = function () {
                                if (xhr2.readyState === DONE){
                                    if (xhr2.status === OK){        
                                        location.href = "http://server/redirected.html";
                                    }
                                }
                            }
                        }
                        xhr2.send("Email="+encodeURIComponent(useremail));
                    }
                }
                xhr.send("username=HSuser&password=SimpleUserPassword");
            }
        };
    
    </script>   
    </body>
    </html>
    

    当前 PHP 代码:

    <?php
    
        require ('connect.php');
    
        $clean_email = "";
        $cleaner_email = "";
    
    
        if(isset($_POST['email']) && !empty($_POST['email'])){
    
            //sanitize with filter
            $clean_email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
            //sanitize with test_input
            $cleaner_email = test_input($clean_email);
            //validate with filter
            if (filter_var($cleaner_email,FILTER_VALIDATE_EMAIL)){
                // email is valid and ready for use
                echo "Email is valid";  
                //Email is a column in the DB
                $stmt = $DB->prepare("INSERT INTO addresses (Email) VALUES (?)");
                $stmt->bind_param("s", $cleaner_email);
                $stmt->execute();
                $stmt->close();
            } else {
                // email is invalid and should be rejected
                echo "Invalid email, try again";
            } 
        } else {
        echo "Please enter an email";
        }
    
    
        function test_input($data) {
          $data = trim($data);
          $data = stripslashes($data);
          $data = htmlspecialchars($data);
          return $data;
        }
    
        $DB->close();   
    ?>
    

    之前的 HTML/JS 代码:

    function SendAjax() {
        var email = document.getElementById("email").value;
        console.log(email);
        // Check if fields are empty 
        if (email=="") {
            alert("Please enter your email.");
        }
        // AJAX code to submit form
        else{
            var xhr = new XMLHttpRequest();
            xhr.open('POST', 'http://router/login', true);
            xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded", "Access-Control-Allow-Origin: *");
    
            xhr.onreadystatechange = function () {
                var DONE = this.DONE || 4;
                if (xhr.readyState === XMLHttpRequest.DONE){
                    var xhr2 = new XMLHttpRequest();
                    xhr2.open('POST', 'http://server/insertDB.php', true);
                    xhr2.setRequestHeader("Content-type", "application/x-www-form-urlencoded", "Access-Control-Allow-Origin: *");
                    var useremail = document.getElementById("email").value;
    
                    xhr2.onreadystatechange = function () {
                        var DONE = this.DONE || 4;
                        if (xhr2.readyState === XMLHttpRequest.DONE) {
                            location.href = "http://server/redirected.html";
                        }
                    };
                    xhr2.send("Email="+encodeURIComponent(useremail));
                }
            }
    
            xhr.send("popup=true&username=HSuser&password=SimpleUserPassword");
        }
    }
    

    最佳答案

    如果它让你的生活更轻松(而且它会),你可以将 jQuery 置于无冲突模式。

    <!-- Putting jQuery into no-conflict mode. -->
    <script src="prototype.js"></script>
    <script src="jquery.js"></script>
    <script>
    
    var $j = jQuery.noConflict();
    // $j is now an alias to the jQuery function; creating the new alias is optional.
    
    $j(document).ready(function() {
        $j( "div" ).hide();
    });
    
    // The $ variable now has the prototype meaning, which is a shortcut for
    // document.getElementById(). mainDiv below is a DOM element, not a jQuery object.
    window.onload = function() {
        var mainDiv = $( "main" );
    }
    
    </script>
    

    https://learn.jquery.com/using-jquery-core/avoid-conflicts-other-libraries/

    然后你就可以进行 AJAX 调用,并且应该等待的内容可以放入 success 函数中:

                $j.ajax({
                    url: '/your-form-processing-page-url-here',
                    type: 'POST',
                    data: yourVariables,
                    mimeType: 'multipart/form-data',
                    success: function(data, status, jqXHR){
                        alert('Hooray! All is well.');
                        console.log(data);
                        console.log(status);
                        console.log(jqXHR);
    
                    },
                    error: function(jqXHR,status,error){
                        // Hopefully we should never reach here
                        console.log(jqXHR);
                        console.log(status);
                        console.log(error);
                    }
                });
    

    关于javascript - Ajax Vanilla JS - ajax 异步继续,无需等待 readState 4,状态 200,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59630438/

    相关文章:

    javascript - 调用函数 'ChartModule' ,不支持函数调用

    javascript - 在具有不同主页的单页应用程序中路由

    php - 如何使用从这个字符串中提取数据

    php - View 中不存在方法 [header] - Laravel 5

    javascript - jquery .click 看不到 .append() 代码

    Javascript (AngularJS) 在大型 DOM 更新期间不会阻塞 UI

    JavaScript 动画在客户端的 IE 9 上卡住,但我的没有。为什么?

    php - 搜索只读到一个关键字 : SQLSTATE[HY093]: Invalid parameter number

    html - 自动播放 &lt;iframe&gt; Youtube 视频 - ?autoplay=1 不工作

    javascript - 页面上的链接在执行后调用 servlet 返回上一页