首页 > 代码库 > asp.net + html页面来实现 ajax 示意——给初学者的参考

asp.net + html页面来实现 ajax 示意——给初学者的参考

静态页面示意代码:

<!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>ajax试验</title>
<script type="text/javascript">
function btnClick() {
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); //创建xmlhttp对象,针对ie浏览器写的,其他浏览器方法不同
if (!xmlhttp) {
alert("创建对象失败");
return false;
}
xmlhttp.open("POST", "GetDate1.ashx?tx" + new Date(), false); //准备向服务器的getdate1.ashx发出Post请求
//xmlhttp的open是异步请求,不会等到拿到数据才返回,因此需要监听xmlhttp对象的onreadystatechange事件
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4) { //xmlhttp执行状态之一,1正在加载对象,2加载完毕,3正在获取数据,4返回数据
if(xmlhttp.status==200) { //返回代码200,为成功,http响应代码
document.getElementById("Text1").value=http://www.mamicode.com/xmlhttp.responseText;//responeText是服务器返回的文本
}
else{
alert("ajax服务器返回错误!");
}
}
}
xmlhttp.send(); //这是才象服务器发送请求
}
</script>
</head>
<body>
<input id="Text1" type="text" />
<input id="Button1" type="button" value="http://www.mamicode.com/button" onclick="btnClick()" />
</body>
</html>

 

一般处理程序示意代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ajax测试1
{
/// <summary>
/// GetDate1 的摘要说明
/// </summary>
public class GetDate1 : IHttpHandler
{

public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write(DateTime.Now.ToString());
}

public bool IsReusable
{
get
{
return false;
}
}
}
}

 

asp.net + html页面来实现 ajax 示意——给初学者的参考