一个简单的客户端调用xmlHttp的例子
客户端调用xmlHttp的过程很简单,只有5个步骤:
1、创建xmlHttp对象
2、打开与服务端的连接,同时定义指令发送方式,服务网页(URL)和请求权限等。
客户端通过Open命令打开与服务端的服务网页的连接。与普通Http指令传送一样,可以用"GET"方法或"POST"方法指向服务端的服务网页。
3、发送指令。
4、等待并接收服务端返回的处理结果。
5、释放xmlHttp对象
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>xmlHttp test</title>
<script type="text/javascript" language="javascript">
function jb() {
var A=null;
try {
A=new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e) {
try {
A=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(oc) {
A=null;
}
}
if ( !A && typeof XMLHttpRequest != "undefined" ) {
A=new XMLHttpRequest();
}
return A;
}
var req = null;
function doRequest() {
req = null;
//创建xmlHttp对象
req = jb();
//如果浏览器不支持,提示错误信息。
if (!req) {
alert("Giving up. Cannot create an XMLHttp instance.");
return false;
}
//定义用来处理接收数据的回调函数
req.onreadystatechange = callback;
/******* 这部分是以post方式提交的用法 ******/
//提交参数内容
var strData = "code=123";
//数据提交的目标位置
var url = "default.asp";
//以post方法,将参数code=123提交给default.jsp去处理
req.open("POST", url, true);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); //用utf-8编码
req.send(strData);
/*******************************************/
/******* 这部分是以get方式提交的用法 ******
//提交参数内容
var strData = "code=123";
//数据提交的目标位置,并将参数以get方式添加到url后面
var url = "default.asp?" + strData;
//以get方法,请求url:default.asp?code=123
req.open("GET", url, true);
req.send(null);
/*******************************************/
}
function callback() {
/* readyState属性能够反映出服务器在处理请求时的进展状况。
0 = uninitialized
1 = loading
2 = loaded
3 = interactive
4 = complete
*/
if (req.readyState == 4) {
/* HTTP status code (i.e., 200, 404, 500, etc.)
完整的状态值可参考w3c的列表:http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
我们只关心值为200的OK相应
*/
if (req.status == 200) {
showResponse();
} else {
alert("There was a problem with the request.");
}
}
}
function showResponse(){
/* 几种返回值的接收方法:
responseBody:结果返回为无符号整数数组。
responseStream:结果返回为IStream流。
responseText :结果返回为字符串。
responseXML:结果返回为XML格式数据。
*/
alert(req.responseText);
}
</script>
</head>
<body>
<input type="button" name="Button" value="发出请求" onclick="doRequest()" />
</body>
</html>
//default.asp 此略
//在服务器端 Post来的用Request.Form("code") 接收
Get来的用Request.QueryString("code")