<title>完整的HttpRequest讲解 createXmlHttpRequest Ajax请求</title>
<script type="text/javascript">
var xmlHttp = false;
//创建HttpRequest对象
function createXmlHttpRequest() {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
xmlHttp = false;
}
}
if (!xmlHttp && typeof XMLHttpRequest != "udefined") {
xmlHttp = new XMLHttpRequest();
}
}
function Call() {
//先创建XMLHttpRequest的对象
createXmlHttpRequest();
//这里可以传递参数
var url = "Handler.ashx";
xmlHttp.open("GET", url, false);
//制定回调函数
xmlHttp.onreadyStateChange = callBackMethod;
//发送
xmlHttp.send(null);
}
//回调函数
function callBackMethod() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {//http请求一切正常
alert("请求以完成 结果:" + xmlHttp.responseText + "看看按钮的值变了没"); //respneseText就是返回值
document.getElementById("Button1").value = xmlHttp.responseText;
} else {
alert("Not able to retrieve description" + XMLHttpReq.statusText);
}
} else {
switch (xmlHttp.readyState) {
case 0:
alert("未初始化 还没有调用send()方法");
break;
case 1:
alert("载入 已调用send()方法,正在发送请求");
break;
case 2:
alert("(载入完成)send()方法执行完成,已经接收到全部响应内容");
break;
case 3:
alert("(交互)正在解析响应内容");
break;
}
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="idv">
<input id="Button1" type="button" value="button" onclick="Call()" />
</div>
</form>
</body>
</html>
一般处理程序内容
<%@ WebHandler Language="C#" class="Handler" %>
using System;
using System.Web;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
}
public bool IsReusable {
get {
return false;
}
}