将PHP结果返回到原始html页面

时间:2013-06-18 14:29:25

标签: php javascript html css ajax

我想将值$newsum返回到col div,它来自php计算到db结果。我想保持html和php文件分开。但是,当这样做时,我不会在index.html页面上得到结果。

我尝试了一些ajax解决方案,但还没有工作,

的index.html

<form id="search" action="index.php" method="post">
    <input type='search' name='keywords' value='' style="width:99%;">
    <a href='#col'>
    <input type='hidden' value='Submit' id='submit' name='doSearch' />
    </a>
</form>

<div  id="col"  style="width:100%; margin:0 auto;">
 <script>
 document.write("<?php echo $newsum.$message; ?>");
  </script>

的index.php

if($_POST['doSearch'] == 'Submit') 
{
    $value=$_POST['keywords'];
    $newsum= round($total,1);

    if($newsum >= 3.5)
   {

   $message=$newsum.'/5';
   }

    }

AJAX

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
  $('#submit').click(function(){

   $.post("index.php", $("#search").serialize(),  function(response) {
   $('#col').html(response);

    });
    return false;

       });

       });
     </script>

1 个答案:

答案 0 :(得分:1)

你错过了搜索结果:

修改index.php

if($_POST['doSearch'] == 'Submit') 
{
  $value=$_POST['keywords'];
  $newsum= round($total,1);
  if($newsum >= 3.5)
  {
     $message=$newsum.'/5';
     echo $message; // added
  }
  else 
  {
     echo "Nope"; // this is only to make sure something at all is echoed.
  }
}

然后改变你的JS:

 // submit action instead of click is the way to use form data


 <script src="http://code.jquery.com/jquery-latest.js"></script>
 <script>
 $(document).ready(function(){
     $('#search').submit(function(e){
        e.preventDefault();
        $.post("index.php", $("#search").serialize(),  function(response) {
           $('#col').html(response);
        });
     });
  });
 </script>

注意

您已将PHP代码添加到HTML文档中。这永远不会奏效......

<script>
 document.write("<?php echo $newsum.$message; ?>"); 
</script>

即使它是PHP文档,变量也不会存在,因为它们是在index.php中设置的。