- CREATE TABLE `directory` (
- `id` INT NOT NULL AUTO_INCREMENT ,
- `name` VARCHAR( 64 ) NOT NULL ,
- `phone` VARCHAR( 16 ) NOT NULL ,
- PRIMARY KEY ( `id` )
- ) TYPE = MYISAM ;
- insert into `directory` (name,phone) values ('Tom Smith', '512-555-0111');
- insert into `directory` (name,phone) values ('Bill Smith', '512-555-0112');
- insert into `directory` (name,phone) values ('John Smith', '512-555-0113');
- insert into `directory` (name,phone) values ('Jane Smith', '512-555-0114');
- insert into `directory` (name,phone) values ('Sara Smith', '512-555-0115');
- <html>
- <head>
- <title>Welcome to Ajax!!</title>
- <script type="text/javascript" src="./jquery.js"></script>
- <script type="text/javascript">
- $(document).ready(function(){
- $("#search_results").slideUp();
- $("#search_button").click(function(e){
- e.preventDefault();
- ajax_search();
- });
- $("#search_term").keyup(function(e){
- e.preventDefault();
- ajax_search();
- });
- });
- function ajax_search(){
- $("#search_results").show();
- var search_val=$("#search_term").val();
- $.post("./find.php",{search_term:search_val},function(data){
- if(data.length>0){
- $("#search_results").html(data);
- }
- }
- )
- }
- </script>
- </head>
- <body>
- <h1> Search Our Phone Directory <h1>
- <form id="searchform" method="post">
- <div >
- <label for="search_term">Search Name/Phone</label>
- <input type="text" name="search_term" id="search_term"/>
- <input type="submit" value="search" id="search_button"/>
- </div>
- </form>
- <div id="search_results"></div>
- </body>
- </html>
- <?php
- define('HOST',"localhost");
- define('USER',"root");
- define('PWD',"");
- define('DB','test');
- $connect = mysql_connect(HOST,USER,PWD) or die("数据库连接失败!");
- mysql_select_db(DB) or die("选择数据库失败");
- $term=$_POST['search_term'];
- //$term="Bill";
- $sql = "select name,phone from directory where name like '%".$term."%' order by name asc";
- //echo $sql;
- $result = mysql_query($sql);
- $string = "";
- if(mysql_num_rows($result)>0){
- while ($row = mysql_fetch_array($result)){
- $string .="<b>".$row['name']."</b>-";
- $string .="<b>".$row['phone']."</b>";
- $string .="<br/>\n";
- }
- }else{
- $string = "No matches";
- }
- echo $string;
再上一节中的$.post()方法是对底层ajax的一个快速封装,那么下边让我们看一看用底层的$.ajax()方法怎么实现上述的功能,简而言之,就是再在js中添加一个函数,代码如下:
接下来然后把上边的那个ajax_search()函数全部替换掉再试试,是不是跟原来的结果一样啊!!!
- function ajax(){
- $("#search_results").show();
- var search_value=$("#search_input").val();
- $.ajax({
- type:"post",
- url:"./find.php",
- data:{'search':search_value},
- success:function(data){
- if(data.length>0){
- $("#search_results").html(data);
- }
- }
- })