搜索结果未显示在同一窗口中

时间:2013-11-12 17:02:24

标签: javascript php html

我的搜索结果没有显示在同一个窗口上,我希望结果显示在同一个窗口中。我找到了同样的问题,但代码与我正在使用的不同,所以我无法与之相关:Search wont show on same page

方案1:

如果我放入action="search_result2.php" - 它会将结果重定向到另一页

方案2:

如果我在下面的代码中使用action="",它没有做任何事情

<html xmlns="http://www.w3.org/1999/xhtml">
<head>

<script>
$(document).ready(function(){
    $("#results").show();
});
</script>

<script type="text/javascript">
    $(document).ready(function(){
        $("#search").on('click',function() {
            var find = $('#find').val();
            var field = $('#field').val();
            $.post('search_result2.php',{find:find, field:field}, function(data){
            $("#results").html(data);
            });
            return false;
        });
    });

</script>
</head>

<body>
<div id="container" style="width:auto">
<div id="mainContent">

 <h2>Search</h2> 
 <form name="search" method="post" action="">
 Seach for: <input type="text" name="find" id="find" /> in 
 <Select NAME="field" id="field">
 <Option VALUE="testA">A</option>
 <Option VALUE="testB">B</option>
 <Option VALUE="testC">C</option>
 <Option VALUE="testD">D</option>
 </Select>
 <input type="hidden" name="searching" value="yes" />
 <input type="submit" name="search" id="search" value="Search" />
 </form>

<div id="results">
</div>
</div>
</div>
</body>
</html>

这是我的search_result2.php:

<?php

 //This is only displayed if they have submitted the form 
if (isset($_POST['searching']) && $_POST['searching'] == "yes") 
{ 
echo "<h2>Results</h2><p>"; 

//If they did not enter a search term we give them an error 
if (empty($_POST['find'])) 
{ 
echo "<p>You forgot to enter a search term"; 
exit; 
} 

 // Otherwise we connect to our Database 
 mysql_connect("host", "username", "passw") or die(mysql_error()); 
 mysql_select_db("testdb") or die(mysql_error()); 

 // We preform a bit of filtering 
 $find = strtoupper($_POST['find']); 
 $find = strip_tags($_POST['find']); 
 $find = trim ($_POST['find']); 
 $field = trim ($_POST['field']);

 //Now we search for our search term, in the field the user specified 
 $data = mysql_query("SELECT * FROM testtable WHERE upper($field) LIKE'%$find%'"); 


 //And we display the results 
 while($result = mysql_fetch_array( $data )) 
 { 
 echo $result['testA']; 
 echo " "; 
 echo $result['testB']; 
 echo "<br>"; 
 echo $result['testC']; 
 echo "<br>"; 
 echo $result['testD']; 
 echo "<br>"; 
 echo "<br>"; 
 } 

 //This counts the number or results - and if there wasn't any it gives them a little message explaining that 
 $anymatches=mysql_num_rows($data); 
 if ($anymatches == 0) 
 { 
 echo "Sorry, but we can not find an entry to match your query<br><br>"; 
 } 

 //And we remind them what they searched for 
 echo "<b>Searched For:</b> " .$find; 
 } 
 ?>

1 个答案:

答案 0 :(得分:1)

如果您想要在不刷新页面的情况下加载同一页面,则需要发出ajax请求。

如果您可以重新加载页面,则php部分必须与原始链接位于相同的“位置”。 例如,如果您将该代码放在带有表单的同一文件的顶部(并使用.php扩展名重命名),它应该可以工作(如果php可以在该文件夹中解释)。