前端
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script type="text/javascript"> onload = function () {
var userName = document.getElementById("tuserName");
var userPwd = document.getElementById("tuserPwd");
var btnGet = document.getElementById("btnGet");
var btnPost = document.getElementById("btnPost");
var divShow = document.getElementById("divDes");
btnGet.onclick = function () {
//发送异步请求
//1、判断是否IE5 IE6 因为IE5、6只支持ActiveXObject
var xhr;
if (XMLHttpRequest) { xhr = new XMLHttpRequest(); } else { xhr=new ActiveXObject("Microsoft.XMLHTTP") }
//open(method---请求的方法【GET或POSt】,url--请求的页面,asyc 是否异步 ,user请求的用户名,pwd密码 )方法
//注:Get请求参数通过 地址 来传送,
var url = "index.ashx?name=" + userName.value + "&password=" + userPwd.value+"&time="+Date.now.toString();
xhr.open("Get", url, true); //3、发送异步请求
xhr.send(); //4、监听请求状态 onreadystatechange 状态改变事件 4为加载成功
xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200)
{
//如果后台返回成功
if (xhr.responseText = "OK") { //location.href = "http://www.baidu.com";
divShow.innerHTML = xhr.responseText; }
else { divShow.innerHTML = xhr.responseText; } } } }
btnPost.onclick = function () { alert("btnPost")
} } </script>
</head>
<body>
<input type="text" id="tuserName" />
<input type="text" id="tuserPwd"/>
<input type="button" id="btnGet" value="btnGet" />
<input type="button" id="btnPost" value="btnPost"/>
<div id="divDes"> </div>
</body>
</html>
后台
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace Ajax练习
{
/// <summary>
/// index 的摘要说明
/// </summary>
public class index : IHttpHandler
{ public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html"; //获取请求到的参数
string name= context.Request["name"];
string password = context.Request["password"]; //执行 处理
if (name == password)
{ //返回结果
context.Response.Write("OK"); }
else
{
//返回结果
context.Response.Write("NG"); } } public bool IsReusable
{
get
{
return false;
}
}
}
}