在ajax html返回中调用ajax会阻止第一个ajax脚本进一步工作

Calling ajax inside ajax html return prevents first ajax script from further working

本文关键字:ajax 第一个 脚本 进一步 工作 html 返回 调用      更新时间:2023-09-26

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
...
...
<form id="validate_mail" action="/wp-content/custom-php/validate_mail.php" method="POST">
    <input name="mail_name" type="text" value="" />
    <input type="submit" value="submit" />
</form>
<div id="validate_mail_result"></div> // placeholder for html code that is returned
<script> // main script
    var form=$('#validate_mail');
    form.submit(function(ev){
        $.ajax({
            type    : form.attr('method'),
            url     : form.attr('action'),
            data    : form.serialize(),
            success : function(result{
                $('#validate_mail_result').html(result);
            }
        });
        ev.preventDefault();
    });
</script>

PHP(由主脚本调用)

<?php
    ...
    ...
    // Connect to MySQL
    $servername = "localhost";
    $username = "myusername";
    $password = "mypassword";
    $connection = new mysqli($servername,$username,$password);
    if (mysqli_connect_errno()){
        printf("MyErrorMsg: %s'n", mysqli_connect_error());
        exit();
    }
    // Perform request
    $mail_name = $_POST[mail_name];
    $full_mail_name = $mail_name . "@mydomain.me";
    $connection->select_db("MAILSERVER");
    $queryMailExists = "SELECT id FROM users WHERE mailname = '" . $mail_name . "'";
    $resultMailExists = $connection->query($queryMailExists);
    $row_cnt = $resultMailExists->num_rows;
    $connection->close();
    if (is_valid_email_address_5321($full_mail_name)==0){
        echo "Not a valid email-address according to RFC5321";
    }elseif(row_cnt==0){ //check if email name allready taken 
        echo "Mail available";
        echo "
        <form id='"purchase_mail'" action='"/wp-content/custom-php/purchase_mail.php'" method='"POST'">
            <input id='"password'" style='"width: 280px;'" name='"password'" type='"password'" value='"'" />
            <div id=pswrd_struct_chk></div>
            <input id='"password_retyped'" style='"width: 280px;'" name='"password_retyped'" type='"password'" value='"'" />
            <div id=pswrd_match_chk></div>
            <script> // this script and the one after this are blocking the main script
                var form=$('#purchase_mail');
                $('#password').keyup(function(ev){
                    $.ajax({
                        type    : form.attr('method'),
                        url     : '"/wp-content/custom-php/password_structure_check.php'",//just checks if the password strength  is weak/acceptable/good
                        data    : form.serialize(),
                        success : function(result){
                            $('#pswrd_struct_chk').html(result);
                        }
                    });
                    $('#password_retyped').val('"'");
                    $('#pswrd_match_chk').html('"'");
                });
            </script>
            <script>
                var form=$('#purchase_mail');
                $('#password_retyped').keyup(function(ev){
                    $.ajax({
                        type    : form.attr('method'),
                        url     : '"/wp-content/custom-php/password_match_check.php'",
                        data    : form.serialize(),
                        success : function(result){
                            $('#pswrd_match_chk').html(result);
                        }
                    });
                });
            </script>
            <input type='"submit'" value='"PAY'" />
        ";
    }else{
         echo "<div>Mailname allready taken!</div>";
    }
?>

当我评论完最后两个脚本时,一切都按预期进行。PHP中的3个不同的if-案例确实将它们的html代码回显到占位符中,但当我在执行"elseif(row_cnt==0)"部分后不注释脚本时,主脚本会被卡住,无论提交了什么(在输入字段中输入id=mail_name),我都不会得到其他两个if-案例的任何回显。

我无法用谷歌搜索我的问题。

感谢您在最后时刻的努力。

当类型为HTML时,AJAX不允许在结果中传递脚本标记。假设您以某种方式成功地传递了脚本,您仍然需要重新触发脚本,这有点麻烦。

我建议您编写html,在成功消息中添加代码,并从PHP传递表单操作、URL等变量。这样你就不会面临这些问题,你也能完成任务。

我检查了您的代码。你可以尝试这样做:第一个AJAX:

$.ajax({
//logic for the first ajax
}).done(function(){
//**second ajax**
})

首先,您应该遵守以下规则:
在php脚本中-只有php代码,没有js和css在js脚本中-只有js,没有css**
它不仅是一个好的风格,它将帮助你方便你的工作!

我只是把你的html和js从validate_mail.php移到主页上,它看起来像:

<html>
    <head></head>
    <body>
        <form id="validate_mail" action="/wp-content/custom-php/validate_mail.php" method="POST">
            <input name="mail_name" type="text" value="" />
            <input id="btn_validate_mail" type="button" value="submit" />
        </form>
        <div id="validate_mail_result1" style="display: none;">Not a valid email-address according to RFC5321</div>
        <div id="validate_mail_result2" style="display: none;">
            Mail available
            <form id="purchase_mail" action="/wp-content/custom-php/purchase_mail.php" method="POST">
                <input id="password" style="width: 280px;" name="password" type="password" value="" />
                <div id="pswrd_struct_chk"></div>
                <input id="password_retyped" style="width: 280px;" name="password_retyped" type="password" value="" />
                <div id="pswrd_match_chk"></div>
            </form>
        </div>
        <div id="validate_mail_result3" style="display: none;">Mailname allready taken!</div>
    </body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script>
        $('#btn_validate_mail').click(function () {
            var form = $('#validate_mail');
            $.ajax({
                type: form.attr('method'),
                url: form.attr('action'),
                data: form.serialize(),
                success: function (result) {
                    $('#validate_mail_result'+result).show();
                },
                error: function (xhr, status, error) {
                    // If you will receive any errors - you will see it here.
                    console.log(error);
                },
                complete: function () {
                    form.hide();
                }
            });
        });
        $('#password').keyup(function(ev){
            var form=$('#purchase_mail');
            $.ajax({
                type    : form.attr('method'),
                url     : "/wp-content/custom-php/password_structure_check.php",//just checks if the password strength  is weak/acceptable/good
                data    : form.serialize(),
                success : function(result){
                    $('#pswrd_struct_chk').html(result);
                }
            });
            $('#password_retyped').val("");
            $('#pswrd_match_chk').html("");
        });
        $('#password_retyped').keyup(function(ev){
            var form=$('#purchase_mail');
            $.ajax({
                type    : form.attr('method'),
                url     : "/wp-content/custom-php/password_match_check.php",
                data    : form.serialize(),
                success : function(result){
                    $('#pswrd_match_chk').html(result);
                }
            });
        });
    </script>
</html>

它看起来好多了,但仍然很糟糕。js不应该在这里,css也应该在这里。

现在validate_mail.php看起来:

<?php
    $servername = "localhost";
    $username = "myusername";
    $password = "mypassword";
    $connection = new mysqli($servername,$username,$password);
    if (mysqli_connect_errno()){
        printf("MyErrorMsg: %s'n", mysqli_connect_error());
        exit();
    }
    // Perform request
    $mail_name = $_POST['mail_name'];
    $full_mail_name = $mail_name . "@mydomain.me";
    $connection->select_db("MAILSERVER");
    $queryMailExists = "SELECT id FROM users2 WHERE mailname = '" . $mail_name . "'";
    $resultMailExists = $connection->query($queryMailExists);
    $row_cnt = $resultMailExists->num_rows;
    $connection->close();
    if (is_valid_email_address_5321($full_mail_name)==0){
        echo 1;
    }elseif($row_cnt==0){ //check if email name allready taken 
        echo 2;
    }else{
         echo 3;
    }

这么简单。。。

我不想谈论xss、sql注入等等,因为你的问题不是关于它的,但你应该记住它。
您需要继续分离js、html和css。。。

我只是想展示一下如何更容易地获得你需要的东西。。。希望它能有所帮助。。。

好消息。你的代码中有错别字。我在本地服务器上运行了相关部分,您的脚本正在按预期执行。享受

HTML

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    </head>
    <body>
        <form id="validate_mail" action="validate_mail.php" method="POST">
            <input name="mail_name" type="text" value="" />
            <input type="submit" value="submit" />
        </form>
        <div id="validate_mail_result"></div>
        <script> // main script
            var form = $('#validate_mail');
            form.submit(function(ev){
                $.ajax({
                    type    : form.attr('method'),
                    url     : form.attr('action'),
                    data    : form.serialize(),
                    // success : function(result{ <-- typo
                    success : function(result){
                        $('#validate_mail_result').html(result);
                    }
                });
                ev.preventDefault();
            });
        </script>
    </body>
</html>

PHP-validate_mail.PHP

<?php
    // }elseif(row_cnt==0){     <-- typos here too, maybe more above, didn't check
    // }else if($row_cnt == 0){ 
        echo "Mail available";
        echo "
        <form id='"purchase_mail'" action='"/wp-content/custom-php/purchase_mail.php'" method='"POST'">
            <input id='"password'" style='"width: 280px;'" name='"password'" type='"password'" value='"'" />
            <div id=pswrd_struct_chk></div>
            <input id='"password_retyped'" style='"width: 280px;'" name='"password_retyped'" type='"password'" value='"'" />
            <div id=pswrd_match_chk></div>
            <script> // this script and the one after this are blocking the main script
                var form=$('#purchase_mail');
                $('#password').keyup(function(ev){
                    $.ajax({
                        type    : form.attr('method'),
                        url     : '"/wp-content/custom-php/password_structure_check.php'",//just checks if the password strength  is weak/acceptable/good
                        data    : form.serialize(),
                        success : function(result){
                            $('#pswrd_struct_chk').html(result);
                        }
                    });
                    $('#password_retyped').val('"'");
                    $('#pswrd_match_chk').html('"'");
                });
            </script>
            <script>
                var form=$('#purchase_mail');
                $('#password_retyped').keyup(function(ev){
                    $.ajax({
                        type    : form.attr('method'),
                        url     : '"/wp-content/custom-php/password_match_check.php'",
                        data    : form.serialize(),
                        success : function(result){
                            $('#pswrd_match_chk').html(result);
                        }
                    });
                });
            </script>
            <input type='"submit'" value='"PAY'" />
        ";
    //}else{
    //    echo "<div>Mailname allready taken!</div>";
    //}
?>

忽略这里已经提到的错误(无效HTML、无效PHP等),最简单(也是最好)的解决方案就是重构代码,这样它就不会返回HTML/JS。只需将PHP当前返回的所有HTML/JS放入页面并隐藏即可。让PHP返回某种状态代码("无效电子邮件"/"ok"/"take"等),并让jQuery隐藏/取消隐藏页面上的相应响应。这样可以在您的演示和业务逻辑之间保持关注点的分离。

如果您使用的是jQuery版本1.7及以上的

更改

var form=$('#validate_mail');
form.submit(function(ev){
    $.ajax({

收件人:

var $(document).on('submit','#validate_mail',function(ev){
    $.ajax({

另外,试着把JQuery脚本放在一起,也许放在一个main.js文件中,当然放在PHP之外。因此,您应该像我描述的那样,直接在#validate_mail提交函数下为#purchase_mail编写JS,当您将表单ajax到页面中时,它就会起作用。

除非您以某种方式评估eval(),否则您使用Ajax获取的脚本将无法工作,但这样做会使您的脚本暴露出潜在的安全漏洞。

希望这能帮助伙计