ajax+php+js实现异步刷新表单验证

创建ajax对象

 1 //创建对象
 2 function createAjax(){
 3     var request =false;
 4     //IE浏览器,window对象存在ActiveXObject属性
 5     if(window.ActiveXObject){
 6         try{
 7              request = new ActiveXObject("Msxml2.XMLHTTP");
 8              }
 9              catch(othermicrosoft){
10               try{
11                request = new ActiveXObject("Microsoft.XMLHTTP");
12               }catch(failed){
13                request = false;
14               }
15             }
16     }
17 
18     //非IE浏览器,window对象存在XMLHttpRequest属性
19     if(window.XMLHttpRequest){
20         request = new XMLHttpRequest();
21 
22         if (request.overrideMimeType) {
23             request.overrideMimeType("text/xml");
24         }
25     }
26     return request;
27 }

页面js语句触发事件

1 <input type="text" id="search_input" placeholder="智能搜索" onkeydown="search('total_marks')" onkeyup="result('total_marks')" style="border-color:#32CD32;border-radius:5px;">

调用的js方法

 1 var content = document.getElementById("total_marks").innerHTML;
 2 
 3 function search(id){
 4 
 5     var search = document.getElementById(id);
 6     search.innerHTML = "<div style='margin-left:200px;'>正在搜索...请稍候...</div>";
 7 }
 8 
 9 //获取数据
10 function search_result(){
11     var ajax = null;
12     // alert(ajax);每次请求都要求使用一个新的XMLHttpRequest
13 
14     var div_ajax = document.getElementById("search_input");
15     var val = div_ajax.value;
16 
17     ajax = createAjax();
18     ajax.onreadystatechange=function(){
19         // alert(ajax.readyState);//可知当状态值为4时,才能取值
20         if(ajax.readyState == 4){
21             // alert(ajax.status);
22             if(ajax.status == 200){
23                 var data = ajax.responseText;//数据都返回在responsetext中
24                 document.getElementById('total_marks').innerHTML = data;
25             }else{
26                 alert('页面请求失败!');
27             }
28         }
29     }
30     url = "../bookmarks/js/search.php?key="+val;
31     //如果使用get,就直接通过url直接将数据传给服务器
32     ajax.open("get",url,true);
33     ajax.send(null);    
34     
35 }
36 
37 
38 function result(id){
39 
40     if (document.getElementById("search_input").value == "") {
41         document.getElementById(id).innerHTML = window.content;
42     }else{
43         setTimeout(search_result,1000)
44     };
45 }

请求的php代码

 1 <?php
 2     //最好设定字符集,不然在ajax中默认的字符集会导致出错
 3     require_once("../db.php");
 4     header("Content-Type:text/html;charset=utf-8");
 5 
 6     $sql = "SELECT icon,content from bookmarks  where title LIKE '%".$_GET['key']."%' order by clicknum";
 7     $result = mysql_query($sql);
 8 
 9     //将多个值存放进数组才能输出,不然会当作一个字符串输出
10     // $arr = array("one"=>"111111","two"=>"222222","three"=>"33333333");
11     // echo json_encode($arr);
12 ?>

 

posted @ 2014-08-24 13:13  Jmingzi  阅读(829)  评论(0编辑  收藏  举报