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

时间:2015-02-06 18:25:44

标签: javascript php jquery html ajax

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代码回显到占位符中,但是当我在#34; elseif(row_cnt==0)&#34; if&#34;部分被执行主脚本卡住了,我没有得到任何回声的其他两个id=mail_name - 无论什么是提交的情况(在输入字段中输入{{1}})。

我无法解决我的问题。

感谢您的时间努力。

6 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:2)

我检查了你的代码。您可以尝试做类似的事情: 第一个AJAX:

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

答案 2 :(得分:2)

首先,您应遵循以下规则:
在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 ......

我只是想说明如何更容易达到你所需要的......希望它会有所帮助......

答案 3 :(得分:2)

好消息。您刚刚在代码中输入了拼写错误。我在本地服务器上运行相关部分,并且脚本按预期执行。享受!

<强> 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>";
    //}
?>

答案 4 :(得分:0)

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

答案 5 :(得分:0)

如果您使用的是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,当你将表单写入页面时它将起作用。

除非您以某种方式评估eval(),否则您使用Ajax提取的脚本将无法运行,但这样做会将您的脚本打开以防止潜在的安全漏洞。

希望有帮助的家伙