我想将值$newsum
返回到从php计算到db结果的coldiv。我想保持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>
您错过了回显搜索结果:
编辑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中设置的。