ajax验证用户名是否存在时,xmlhttp.readyState返回的结果总是不是4
刚开始学习ajax,写了一个验证用户名是否存在的小例子,但是运行的时候总是执行alert("ddd");也就是xmlhttp.readyState!=4,这是怎么回事呢?
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %><!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 runat="server"> <title>无标题页</title> <script type="text/javascript"> var xmlhttp; function createXMLHttpRequest(){ if(window.ActiveXObject){ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } else if(window.XMLHttpRequest){ xmlHttp=new XMLHttpRequest(); } } function checkUsername(){ createXMLHttpRequest(); var val=document.getElementById("txtname").value; var url="check.ashx?uname=" + val +"&date="+new Date().getTime(); xmlhttp.open("GET",url,true); xmlhttp.onreadystatechange=showresult; xmlhttp.send(null); document.getElementById("a").style.display="block"; document.getElementById("a").style.background="#fdfde3"; document.getElementById("a").style.border="1px solid #f3f3cc"; document.getElementById("a").innerHTML="正在检查,请稍候……"; } function showresult(){ if(xmlhttp.readyState==4){ if(xmlhttp.status==200){ alert("aa"); var res=xmlhttp.responseText; document.getElementById("a").innerHTML=res; } else alert("bbb"); } else alert("ddd"); }</script></head><body> <form id="form1" runat="server"> <div> <table> <tr> <th> 用户名: </th> <td> <input type="text" id="txtname" onblur="checkUsername()" /><span id="a"></span> </td> </tr> </table> </div> </form></body></html><%@ WebHandler Language="C#" Class="Handler" %>using System;using System.Web;using System.Collections;using System.Collections.Generic;using BLL;using Models;public class Handler : IHttpHandler{ public void ProcessRequest(HttpContext context) { //context.Response.ContentType = "text/plain"; //context.Response.Write("Hello World"); string names = context.Request.QueryString["uname"]; int i = BLL.VipManager.GetRowsByName(names); if (i != 0) { context.Response.Write("抱歉,用户名已被使用。"); } else { context.Response.Write("恭喜,用户名可以使用。"); } } public bool IsReusable { get { return false; } }}
if(xmlhttp.status==200){
alert("aa");
var res=xmlhttp.responseText;
document.getElementById("a").innerHTML=res;
}
else alert("bbb");
}
else alert("ddd");
这里if,else 是平级的,而且xmlhttp.readyState 有5个值0,1,2,3,4,着五个值,最后成功时才显示4,在不成功的时候就调用了alert("ddd");了
[解决办法]
context.Response.Clear();
context.Response.Write("恭喜,用户名可以使用。");
context.Response.End();