需要的文件:Complex.ashx,2_UseAsyncCommLayer.aspx
Complex.ashx中代码如下:
<%@ WebHandler Language="C#" Class="Complex" %>
using System;
using System.Web;
using System.Data.SqlClient;
public class Complex : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
context.Response.ContentType = "text/plain";
string action = context.Request.Headers["action"];
if (action == "normal")
{
try
{
string StrConn = "server=XIATIAN;database=GUOFENG;uid=sa;pwd=sa";
SqlConnection conn = new SqlConnection(StrConn);
conn.Open();
string StrSql = "select count(*) from Users where UsersName='" + context.Request.Params["data"].ToString() + "'";
SqlCommand comm = new SqlCommand(StrSql, conn);
int i = (int)comm.ExecuteScalar();
if (i > 0)
{
context.Response.Write("存在");
}
else
{
context.Response.Write("不存在");
}
}
catch(Exception ex)
{
context.Response.Write(ex);
}
}
else
{
System.Threading.Thread.Sleep(10000);
}
}
public bool IsReusable
{
get {
return false;
}
}
}
2_UseAsyncCommLayer.aspx中代码如下
<script language="javascript" type="text/javascript">
var webRequest=null;
function sendRequest(action)
{
webRequest=new Sys.Net.WebRequest();
webRequest.set_url("handlers/Complex.ashx");
webRequest.get_headers()["action"]=action;
webRequest.set_body("data="+encodeURIComponent(document.getElementById("txt1").value));
webRequest.set_httpVerb("POST");
webRequest.set_timeout(3000);
webRequest.add_completed(onCompleted);
webRequest.invoke();
}
function onCompleted(response,eventArgs)
{
if(response.get_aborted())
{
alert("Response Aborted!");
}
else if(response.get_responseAvailable())
{
var statusCode=response.get_statusCode();
if((statusCode<200)||(statusCode>=300))
{
alert("Error occurred");
}
else
{
alert(response.get_responseData());
}
}
else if(response.get_timedOut())
{
alert("Request timed out!");
}
else
{
alert("Error occurred!");
}
}
</script>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="scriptmanager1" runat="server" ></asp:ScriptManager>
<input type="text" id="txt1" οnblur="sendRequest('normal')"/>
</div>
</form>