AJAX

来源:互联网 发布:机器人编程入门教程 编辑:程序博客网 时间:2024/05/16 18:14
一、什么是 AJAX ?
AJAX = 异步 JavaScript 和 XML。
AJAX 是一种用于创建快速动态网页的技术。
通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
JS调用AJAX引擎代替了表单提交发送HTTP请求。


二、AJAX前台的XMLHttpRequest 对象
XMLHttpRequest组件是AJAX引擎,它用于在后台与服务器交换数据。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
实例:
<html>
<head>
<script type="text/javascript">
function loadXMLDoc(){
/* AJAX script goes here,下面提到的XHR代码都可以写在这里*/
}
</script>
</head>
<body>
<div id="myDiv"><h3>Let AJAX change this text</h3></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
1.XHR创建对象
/*为了应对所有的现代浏览器,包括 IE5 和 IE6,请检查浏览器是否支持 XMLHttpRequest 对象。如果支持,则创建 XMLHttpRequest 对象。如果不支持,则创建 ActiveXObject */
var xmlhttp;
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
}else{// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
2.XHR向服务器发送请求
(1)语法:
xmlhttp.open("GET","demo_get.asp",true);//三个参数分别为:请求的类型(POST|GET)、服务器上文件的地址URL、 是否异步处理请求async(true|false)。
xmlhttp.send();//send()可以包含一个String类型参数,但仅用于POST请求
        同步:提交请求->等待服务器处理->处理完毕返回 这个期间客户端浏览器不能干任何事
        异步async: 请求通过事件触发->服务器处理(这是浏览器仍然可以作其他事情)->处理完毕
(2)在上面的例子中,您可能得到的是缓存的结果。为了避免这种情况,请向 URL 添加一个唯一的 ID:
xmlhttp.open("GET","demo_get.asp?t=" + Math.random(),true);
xmlhttp.send();
(3)如果您希望通过 GET 方法发送信息,请向 URL 添加信息:
xmlhttp.open("GET","demo_get2.asp?fname=Bill&lname=Gates",true);
xmlhttp.send();
(4)如果需要像 HTML 表单那样 POST 数据,请使用 setRequestHeader() 来添加 HTTP 头。然后在 send() 方法中规定您希望发送的数据:
xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");//两个参数分别为头的名称、头的值
xmlhttp.send("fname=Bill&lname=Gates");
(5)当使用 async=true 时,请规定在响应处于 onreadystatechange 事件中的就绪状态时执行的函数:
xmlhttp.onreadystatechange=function(){
  if (xmlhttp.readyState==4 && xmlhttp.status==200){
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","test1.txt",true);
xmlhttp.send();
(6)当使用 async=false 时,不要编写 onreadystatechange 函数,把代码放到 send() 语句后面即可:
xmlhttp.open("GET","test1.txt",false);
xmlhttp.send();
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
3.XHR服务器响应
(1)responseText 属性
/*如果来自服务器的响应并非 XML,请使用 responseText 属性,responseText 属性返回字符串形式的响应。*/
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
(2)responseXML 属性
/*如果来自服务器的响应是 XML,而且需要作为 XML 对象进行解析,请使用 responseXML 属性。*/
xmlDoc=xmlhttp.responseXML;
txt="";
x=xmlDoc.getElementsByTagName("book");
for (i=0;i<x.length;i++){
  txt=txt + x[i].childNodes[0].nodeValue + "<br />";
  }
document.getElementById("myDiv").innerHTML=txt;
/*xmlhttp请求的 books.xml文件如下*/
<bookstore>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
</book>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
</book>
</bookstore>
4.onreadystatechange 事件
  XMLHttpRequest 对象的三个重要的属性。
1)onreadystatechange属性:每当 readyState 属性改变时,就会调用该函数。
2)readyState属性:存有 XMLHttpRequest 的状态。0 - 请求未初始化;1 - 服务器连接已建立;2 -  请求已接收;3 - 请求处理中;4 -  请求已完成,且响应已就绪。
3)status属性:200 - "OK";404 - 未找到页面。
当 readyState 等于 4 且状态为 200 时,表示响应已就绪:
5.使用 Callback 函数
callback 函数是一种以参数形式传递给另一个函数的函数。
如果网站上存在多个 AJAX 任务,那么应该为创建 XMLHttpRequest 对象编写一个标准的loadXMLDoc函数。每个 AJAX 任务调用loadXMLDoc函数,当服务器响应就绪后调用各自的回调函数。
function onButtonClickFunction(){
loadXMLDoc("ajax_info.txt",callback_1);
loadXMLDoc("books.xml",callback_2);
}


function loadXMLDoc(url,callback){
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }else{// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=callback;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}


function callback_1(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
    document.getElementById("myDiv_1").innerHTML=xmlhttp.responseText;
}
}


function callback_2(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
xmlDoc=xmlhttp.responseXML;
txt="";
x=xmlDoc.getElementsByTagName("book");
for (i=0;i<x.length;i++){
  txt=txt + x[i].childNodes[0].nodeValue + "<br />";
  }
    document.getElementById("myDiv_2").innerHTML=xmlhttp.responseText;
}
}






三、AJAX后台的ASP/PHP
1.前台的XMLHttpRequest 对象除了可以请求.xml文件以外,还可以请求.asp与.php等后台文件。假设前台向后台gethint.asp(或gethint.php)传入一个参数q,代码如下:
var index="1";
xmlhttp.open("GET","gethint.asp?q="+str,true);
//或者xmlhttp.open("GET","gethint.php?q="+str,true);
xmlhttp.send();
2.ASP后台代码可以通过request对象的querystring()方法获得参数q,通过response的write()方法返回响应,gethint.asp代码如下:
        Request.Form主要以POST方式来获取值,Request.QueryString主要以GET方式来获取值。
        Request.QueryString.Get("**")跟Request.Form.Get("**")一样原理,可以获取空值。
        还有就是有的会直接用Request去获取参数,这样程序会在Request.QueryString和Request.Form中都查询一遍变量,但是优先获取GET方式提交的数据,即Request.QueryString。
<%
response.expires=-1


dim a(30)
'用名字来填充数组
a(1)="Anna"
a(2)="Brittany"
a(3)="Cinderella"


'获得来自 URL 的 q 参数并转为数字
q=CInt(request.querystring("q"))
r="Please input index from 1 to 3"
for i=1 to 30
if q=i then
r=a(i)
end if
next


'输出结果
response.write(r)
%>
3.PHP后台代码可以通过$_GET[]获得参数q,通过echo返回响应,gethint.php代码如下:
<?php
// 用名字来填充数组
$a[]="Anna";
$a[]="Brittany";
$a[]="Cinderella";


//获得来自 URL 的 q 参数并转为数字 
$q=intval($_GET["q"]);
$r="Please input index from 1 to 3";
for($i=0; $i<count($a); $i++)
{
if($q==$i)
{
$r=$a[$i];
}
}


//输出响应
echo $r;
?>


四、AJAX XML 文件
 AJAX 可以用来读取来自 XML 文件的信息,具体如上面XHR响应的responseXML 属性所述。






五、AJAX 数据库
通过 AJAX 从数据库读取信息。这里以ASP后台为例,前台通过url向后台传输一个参数q(条件字符串)后;后台获取该参数,向数据库查询,并将查询结果返回。
<%
response.expires=-1
sql="SELECT * FROM CUSTOMERS WHERE CUSTOMERID="
sql=sql & "'" & request.querystring("q") & "'"


set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open(Server.Mappath("/db/northwind.mdb"))
set rs=Server.CreateObject("ADODB.recordset")
rs.Open sql,conn


response.write("<table>")
do until rs.EOF
  for each x in rs.Fields
    response.write("<tr><td><b>" & x.name & "</b></td>")
    response.write("<td>" & x.value & "</td></tr>")
  next
  rs.MoveNext
loop
response.write("</table>")
%>
0 0
原创粉丝点击