html 异步调用

来源:互联网 发布:海湾主机编程软件 编辑:程序博客网 时间:2024/05/17 03:07
<!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 >
<title>XMLHttpRequest例子</title>
<script language="javascript" src="ajaxquery.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server" action="WebForm2.aspx">
<div>
<input type="button" value="调用WebService" onclick="callServer()"/>
<span id="showmsg"></span>
<input type="submit" value="提交数据"/>
<input type="text" name="ID" />
</div>
</form>
</body>
</html>







function createHttpRequest() {
var httpRequest = null;
if (window.XMLHttpRequest)
{
httpRequest = new XMLHttpRequest();
return httpRequest;
}

if (window.ActiveXObject) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (ex) {
alert("创建XMLHTTPRequest对象失败!");
}

}

}

return httpRequest;

}


function callServer() {
var http_request = createHttpRequest();
if (http_request == null) {
return;
}
/*
我们的实例在 open() 的第三个参数中使用了 "true"。
该参数规定请求是否异步处理。
True 表示脚本会在 send() 方法之后继续执行,而不等待来自服务器的响应。
onreadystatechange 事件使代码复杂化了。但是这是在没有得到服务器响应的情况下,防止代码停止的最安全的方法。
通过把该参数设置为 "false",可以省去额外的 onreadystatechange 代码。如果在请求失败时是否执行其余的代码无关紧要,那么可以使用这个参数。
*/
http_request.open("GET", "http://10.5.45.72/agv/Handler1.ashx", true);
//向服务器发送请求
http_request.send();
//当readyState属性改变的时候调用的事件句柄函数。当 readyState 为 3 时,它也可能调用多次。
http_request.onreadystatechange = function () {
//HTTP 请求的状态.当一个 XMLHttpRequest 初次创建时,这个属性的值从 0 开始,直到接收到完整的 HTTP 响应,这个值增加到 4
if (http_request.readyState == 4) {
//指定了请求的 HTTP 的状态代码(200表示正常,404表示未找到)
if (http_request.status == 200) {
document.getElementById("showmsg").innerHTML = http_request.responseText;
}
}
}
}
0 0