过年时比较忙,所以一直没有继续写,下面恢复我的学习历程,呵呵。另:高手绕到吧,怕丢人哩
在我前面的学习过程中,我们可以发现,我一直是在使用简单的js来实现AJAX效果 ,但是这样是不通用的,是不能代码重用的,所以代码是需要改进的,经过一些查阅我改进了我的代码,这次是进行数据库连接的例子。
首先是将核心的js代码放到一个js文件中,比如文件名叫做AJAX.js:
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
//创建XMLHTTPRequest对象
function CreateXMLHTTPRequest()
{
//定义一个xmlhttprequest对象,此时为空
var xmlreq=null;
//做简单的IE或非IE判断
if(window.ActiveXObject)
{
xmlreq=new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest)
{
xmlreq=new XMLHttpRequest();
}
return xmlreq;
}
//向服务器端异步提交
//method参数为提交的方式,GET或者POST
//url为提交的页面地址
//回调函数
//contentType返回值的类型,text或者XML
//content:GET请求为null,POST请求为请求头信息
function TalkToServer(method,url,callback,contentType,content)
{
//得到XMLHTTPRequest对象
var req=CreateXMLHTTPRequest();
req.onreadystatechange=getReadyStateHandler(req,callback,contentType);
req.open(method,url,true);
//由于POST和GET的提交方式不同,所以需要进行判断写头
if(method=="POST")
{
req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
}
req.send(content);
}
//判断是否完成和调用回调函数
function getReadyStateHandler(req,callback,contentType)
{
return function()
{
if(req.readyState==4 && req.status==200)
{
if(contentType=="Text")
{
callback(req.responseText);
}
if(contentType=="XML")
{
callback(req.responseXML);
}
}
}
}
下面是在aspx页中进行编码,此时就是调用了,我们来看:
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
<%@ 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" src="AJAX.js"></script>
<script type ="text/javascript" language="javascript">
function check()
{
var txtname = document.getElementById("Text1").value;
TalkToServer("GET","AJAXHandler.ashx?name="+txtname,checkname,"Text",null);
}
function checkname(content)
{
var user=document.getElementById("user");
user.innerHTML=content;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table >
<tr>
<td><div id="show">
<input id="Text1" type="text" onblur="check();" />
</div>
</td>
<td>
<div id="user"></div>
</td>
</tr>
</table>
<br /><a href="javascript:void(0);" onclick="check();">确定</a>
</div>
</form>
</body>
</html>
与此aspx页相对应的aspx.cs页并没有代码,那么如何与服务器端进行交互呢?这里用到了.ashx文件,使用它来接受参数和进行运算:
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
<%@ WebHandler Language="C#" Class="AJAXHandler" %>
using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Threading;
public class AJAXHandler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
//context.Response.AddHeader("Cache-Control", "no-cache");
string name=context.Request.QueryString["name"].ToString();
if (!String.IsNullOrEmpty(name))
{
SqlConnection conn = new SqlConnection(@"Data Source=.;Initial Catalog=test;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
string str = "select count(*) from users where name=@name";
cmd.CommandText = str;
SqlParameter[] parm = new SqlParameter[]
{
new SqlParameter("@name",name)
};
foreach (SqlParameter p in parm)
{
cmd.Parameters.Add(p);
}
conn.Open();
int i = Convert.ToInt32(cmd.ExecuteScalar());
if (i != 0)
{
context.Response.Write("<font color='red'>用户名已存在!</font>");
}
else
{
context.Response.Write("可以注册!");
}
}
else
{
context.Response.Write("用户名不能为空!");
}
}
public bool IsReusable {
get {
return false;
}
}
}
由此来实现异步发送请求,并在服务器端进行运算和返回结果。
欢迎广大同仁和园内大神进行拍砖。