【问题标题】:Calling ajax inside ajax html return prevents first ajax script from further working在 ajax html return 中调用 ajax 会阻止第一个 ajax 脚本进一步工作
【发布时间】:2015-04-01 20:26:30
【问题描述】:

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-case 确实将它们的 html 代码回显到占位符中,但是当我在执行“elseif(row_cnt==0)”部分后不注释脚本时,主脚本卡住了,我没有得到任何回显其他两个if-case 无论提交什么(在输入字段中输入id=mail_name)。

我无法通过谷歌搜索我的问题。

感谢您的付出。

【问题讨论】:

  • 这似乎是一种验证电子邮件的混乱方式?为什么不创建一个仅检查 DB 的简单 PHP 脚本,并将 javascript 从 getgo 保留在主页上。
  • PHP 响应中缺少&lt;/form&gt; 标记是错字吗? success : function(result{ 的语法似乎也不正确(在 HTML 中)。
  • row_cnt 需要 $... 这是一个 PHP 脚本,对吗?你有没有看过你的错误日志?他们会提到这个...... :-D
  • “当我注释掉最后两个脚本时,一切都按预期工作” 很难弄清楚最后两个脚本是什么意思。
  • 好消息,您的代码在我的本地服务器上运行良好。只需修复一些可能导致您的代码卡住的拼写错误。请检查我的答案。

标签: javascript php jquery html ajax


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    我检查了你的代码。您可以尝试执行以下操作: 第一个 AJAX:

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

    【讨论】:

      【解决方案3】:

      首先你应该遵守规则:
      在 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...

      我只是试图展示如何更容易地满足您的需求...希望它会有所帮助...

      【讨论】:

        【解决方案4】:

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

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

        【讨论】:

        • 您好,您能否确认这确实解决了您的问题?
        【解决方案5】:

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

        【讨论】:

          【解决方案6】:

          如果你使用 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 之外并远离您的 PHP。所以你应该像我描述的那样直接在你的#validate_mail提交函数下为#purchase_mail编写JS,当你将表单ajax到页面中时它会起作用。

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

          希望对你有帮助

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-08-20
            • 1970-01-01
            • 1970-01-01
            • 2018-01-05
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多