如何提交HTML表单,使用ajax进行处理,并在同一页面上显示DIV中的PHP变量


How to submit an HTML form, process with ajax, and display PHP variable in DIV on same page

我一直不愿意打开一个问题,但在与这个问题斗争了6个多小时后,我现在斗鸡眼了。我对PHP和HTML有一些经验,但Ajax和jQuery对我来说是新的(我昨天第一次听说它)。

我希望页面在div class="result"中显示提交的值,而不刷新。总之,工作流程:

j.php加载>用户填写两个文本字段(电话和gz)>单击提交按钮>调用jpost.php并返回echos变量>需要在j.php 上显示的php变量是div class=result

j.php=

<html>
<head>
<script src="//code.jquery.com/jquery-latest.js"></script> <!-- load jquery via CDN -->
<script>
   $(document).ready(function() {//start document ready
      $('#submit-button').click(function (){
        $.ajax({
        type: 'POST',
        url: 'jpost.php',
        data: $("#cdr").serialize(),
success: function(d){
   $(".result").html(d);
}
    });
  });
 });//end document ready
</script>
</head>
<body>
<div id="cdr">
 <div>  
   <input type="text" id="phone" name="phone" value="" placeholder="phone" size="40" />
 </div>
 <div> 
  <input type="text" id="gz" name="gz" value="" placeholder="gz" size="40" />
 </div>
 <div>
   <button id="submit-button">Submit</button>
 </div>
</div>
   <div class="result"></div>
</body>
</html>

jpost.php

<?php
    $phone = $_POST['phone'];
    $gz = $_POST['gz'];
echo $phone;
echo $gz;
print_r($_POST);
  echo "grrrr"
?>

所以我只想$gz和$phone在j.php上的结果div中回显,但显示的只是:
阵列()grrrr

这让我相信我的变量在某个地方丢失了:p或我错误地呼应了它们。

非常感谢您的帮助!

问题是:

1.您需要一个表单来串行化数据(而不是div)2。您需要防止事件的默认行为

为了串行化数据,您需要一个表单。我创建了id为#cdr-form的表单此外,您需要确保使用e.preventDefault()防止按钮(事件)的默认行为。在这里阅读更多关于

<html>
<head>
<script src="//code.jquery.com/jquery-latest.js"></script> <!-- load jquery via CDN -->
<script>
   $(document).ready(function() {//start document ready
      $('#submit-button').click(function (e){
        e.preventDefault();
        $.ajax({
        type: 'POST',
        url: 'http://localhost/~metaly/tests/j.php',
        data: $("#cdr-form").serialize(),
success: function(d){
   $(".result").html(d);
}
    });
  });
 });//end document ready
</script>
</head>
<body>
<div id="cdr">
<form id="cdr-form">
 <div>  
   <input type="text" id="phone" name="phone" value="" placeholder="phone" size="40" />
 </div>
 <div> 
  <input type="text" id="gz" name="gz" value="" placeholder="gz" size="40" />
 </div>
 <div>
   <button id="submit-button">Submit</button>
 </div>
 </form>
</div>
   <div class="result"></div>
</body>
</html>