使用Ajax(入门)

如何使用ajax。

1. 创建一个能链接两个异世界的接口
var xmlhttp;

2. 不同世界用不同的接口
if (str.length==0) { document.getElementById("txtHint").innerHTML=""; return; } if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); }

3. 开启世界交互大门
xmlhttp.onreadystatechange

4. 嘿,对面的,你们那边状态如何?
xmlhttp.readyState == 4 (I’M OK COME ON!)
xmlhttp.status == 200 (I’M OK COME ON!)

相关说明:
0: 请求未初始化
1: 服务器连接已建立
2: 请求已接收
3: 请求处理中
4: 请求已完成,且响应已就绪
200: “OK”
404: 未找到页面

5. 我要他们那边的%¥……%……东西~ //doing

6. 5步骤完毕后发送请求链接
xmlhttp.open("GET","test1.txt",true);

相关说明:
open(method,url,async)
规定请求的类型、URL 以及是否异步处理请求。
method:请求的类型;GET 或 POST
url:文件在服务器上的位置
async:true(异步)或 false(同步)

为防止缓存可变为
xmlhttp.open("GET","demo_get.asp?t=" + Math.random(),true);
xmlhttp.send();

7. 点击确认~发射!xmlhttp.send();

相关说明:
send(string)
将请求发送到服务器。
string:仅用于 POST 请求

完整的ajax示例

//coding以下的部分为请求到数据后的处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
function showText(str){
//创建ajax对象
var xmlHttp = null;
//判断是否空值
if(str=="")
{
//coding
document.getElementById("ID").innerHTML="";
return;
}
//根据不同的浏览器建立不同的接口
if(window.XMLHttpRequest)
{
//IE7+ firefox,chorme,o,safari,webkit
xmlHttp = new XMLHttpRequest();
}
else
{
// IE6-
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//主人,我准备好了~ 出发吧
xmlHttp.onreadystatechange=function(){
//芝麻开门
if(xmlHttp.readyState==4 && xmlHttp.status==200)
{
//coding
document.getElementById("ID").innerHTML = xmlHttp.responseText;
}
}
//配置异世界链接隧道
xmlHttp.open("GET","AjaxText.php?q="+str,true);
//关闭通道
xmlHttp.send();
}

当页面有多个ajax请求时:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var xmlhttp;
function loadXMLDoc(url, cfunc) {
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 = cfunc;
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function showText(str) {
loadXMLDoc("AjaxText.php?q=" + str, function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//coding
document.getElementById("result").innerHTML = xmlHttp.responseText;
}
});
}