php搜索功能用javascript动态显示结果

时间:2014-04-17 08:53:50

标签: javascript php search

我有以下PHP脚本,它运行正常,它使用搜索词并将其与几个不同的字段进行比较,然后打印出匹配的每个记录:

<?php

mysql_connect ("localhost", "root","")  or die (mysql_error());  

mysql_select_db ("table"); 

$search = isset($_POST['search']) ? $_POST['search'] : '';

$sql = mysql_query("select * from asset where 
                             name like '%$search%' or 
                             barcode like '%$search%' or
                             serial like '%$search%' ");  

while ($row = mysql_fetch_array($sql)){  

    echo '<br/> Name: '.$row['name'];
    echo '<br/> Barcode: '.$row['barcode'];
    echo '<br/> Serial: '.$row['serial']; 

    }

?>

这是链接到它的表单:

<form action="http://localhost/test/search.php" method="post">
 Search: <input type="text" name="search" /><br />
<input type="submit" name="submit" value="Submit" />
</form>

我需要一些如何对搜索结果进行编码,以便我可以在javascript函数中使用它们,然后我可以在表单下方的同一个html页面上显示它们。

1 个答案:

答案 0 :(得分:0)

为此你必须使用AJAX。您可以使用JSON将数据发送回同一页面。
建议 - 不要使用mysql_ *函数,因为它们已被弃用。学习mysqli_ *并尝试使用它。

<script>
$(function(ev){
   ev.preventDefault();

   $("form").on('submit', function(){
       var form = $(this);
       var url = form.attr('action');
       var data = form.serialize();

       $.post(url, data)
       .done(function(response){

            if(response.success == TRUE)
            {
                  // Search result found from json
                  // You have to loop through response.data to display it in your page
                  // Your single loop will have something like below -

                  var name = response.data.name;
                  var barcode = response.data.barcode;
                  var serial = response.data.serial;

                  $("#name").html(name);
                  $("#barcode").html(barcode);
                  $("#serial").html(serial);
            }
            else
            {
                  // search result not found
            }

       });
   });
});
</script>

search.php

<?php
mysql_connect ("localhost", "root","")  or die (mysql_error());
mysql_select_db ("table");
$search = isset($_POST['search']) ? $_POST['search'] : '';

$sql = mysql_query("select * from asset where 
                         name like '%$search%' or 
                         barcode like '%$search%' or
                         serial like '%$search%' ");

$num = mysql_rows_nums($sql);

$json = array();
if($num > 0)
{
    $json['success'] = TRUE;
    while ($row = mysql_fetch_array($sql)){  
      $json['data']['name'] = $row['name'];
      $json['data']['barcode'] = $row['barcode'];
      $json['data']['serial'] = $row['serial'];
    }
}
else
{
    $json['success'] = FALSE;
}

return json_encode($json);

&GT;