如何在序列化的 Ajax .post 中限制 html(info) 的输出响应

How to limit the output response of html(info) in a serialized Ajax .post

我正在使用此表格和 jquery post 代码段(以及下面的自我 posting 表格)

 <form id="form1" name="form1" method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES, 'utf-8');?>">
   <input type="text" name="username" id="username" />
   <button id="submit">Submit</button> 
</form>
<div id="results"></div>

 <script language="JavaScript" type="text/JavaScript">
   $(document).ready(function() {
     $("#username").blur(function() {
       if ($('#username').val() != '' ) {
          $.post( $("#form1").attr("action"), 
                  $("#form1 :input").serializeArray(),
                  function(info){ 
                        $("#results").html(info);
                  });
        }
     });

   });
 </script>

与 php

 etc...
 $numRows = $stmt->rowCount();
 if($numRows > 0) echo '<strong class="dred">Hey, you\'re already registered.</strong>';
 if($numRows < 1) echo '<strong class="dgreen">O.K.</strong>';

检查数据库中是否存在用户名,并将正确的消息放入#results。

有效,但在#results 中,响应还再次包含表单输入字段和提交按钮。 我如何更改此功能以将进入#results 的数据限制为仅指定的消息。谢谢,我仍然是 Ajax.

的菜鸟
 function(info) {$("#results").html(info);}); 

当您在 post 表单中使用 ajax 时,您需要停止表单输出。

<?php

if(!empty($_POST['username'])){
    //process form here and 
    if($numRows > 0) echo '<strong class="dred">Hey, you\'re already registered.</strong>';
    if($numRows < 1) echo '<strong class="dgreen">O.K.</strong>';
    exit(); //exit so no more output goes.

} 

?>

 <form id="form1" name="form1" method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES, 'utf-8');?>">
 <input type="text" name="username" id="username" />
 <button id="submit">Submit</button> </form><div id="results"></div>

另一种选择是在 jQuery

中过滤您的 HTML
$.post($("#form1").attr("action"), $("#form1 :input").serializeArray(), function(info){ 
    html = $(info).find('#results');
    $("#results").html(html);
});

<?php
//then make sure your message goes into that div
echo'<div id="results">';
if($numRows > 0) echo '<strong class="dred">Hey, you\'re already registered.</strong>';
if($numRows < 1) echo '<strong class="dgreen">O.K.</strong>';
echo'</div>';
?>

当您对表单本身所在的同一个文件执行 ajax 操作时,您会收到包含结果的表单字段的响应。

您应该对不同的文件执行 ajax,您应该只执行数据库查询和 return 结果。

<!-- ajax code -->
<script language="JavaScript" type="text/JavaScript">
   $(document).ready(function() {
     $("#username").blur(function() {
       if ($('#username').val() != '' ) {
          $.post( "some_other_file.php", 
                  $("#form1 :input").serializeArray(),
                  function(info){ 
                        $("#results").html(info);
                  });
        }
     });

   });
 </script>

 <!-- php code -->
 /*some_other_file.php*/

 $numRows = $stmt->rowCount();
 if($numRows > 0) echo '<strong class="dred">Hey, you\'re already registered.</strong>';
 if($numRows < 1) echo '<strong class="dgreen">O.K.</strong>';