1,用ajax做注册页面用户名提示
加入已经存在相同用户名,则提示用户,不存在则提示用户可以注册
前台代码:
View Code
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Ajax._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 id="Head1" runat="server">
<title></title>
<script type="text/javascript">
function sa() {
var a = document.getElementById("Text1").value;
var httphtml =new ActiveXObject("Microsoft.XMLHTTP");
if (!httphtml) {
alert("httphtml异常");
returnfalse;
}
httphtml.open("POST", "Handler1.ashx?name="+ encodeURI(a), false);
httphtml.onreadystatechange = function() {
if (httphtml.readyState ==4) {
//状态码是200则成功
if (httphtml.status ==200) {
//将ajax请求处理后返回的值显示出来
document.getElementById("div").innerHTML = httphtml.responseText;
alert(a);
} else {
alert("ajax请求错误!");
}
}
}
httphtml.send();
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
<input id="Text1" type="text" onblur="sa()"/>
</td>
</td>
</tr>
<tr>
</tr>
</table>
<div id="div">
</div>
<input id="Button1" type="button" value="button"/>
</div>
</form>
</body>
</html>
<!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 id="Head1" runat="server">
<title></title>
<script type="text/javascript">
function sa() {
var a = document.getElementById("Text1").value;
var httphtml =new ActiveXObject("Microsoft.XMLHTTP");
if (!httphtml) {
alert("httphtml异常");
returnfalse;
}
httphtml.open("POST", "Handler1.ashx?name="+ encodeURI(a), false);
httphtml.onreadystatechange = function() {
if (httphtml.readyState ==4) {
//状态码是200则成功
if (httphtml.status ==200) {
//将ajax请求处理后返回的值显示出来
document.getElementById("div").innerHTML = httphtml.responseText;
alert(a);
} else {
alert("ajax请求错误!");
}
}
}
httphtml.send();
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
<input id="Text1" type="text" onblur="sa()"/>
</td>
</td>
</tr>
<tr>
</tr>
</table>
<div id="div">
</div>
<input id="Button1" type="button" value="button"/>
</div>
</form>
</body>
</html>
处理请求的httphandler的页面:
View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
using System.Configuration;
namespace Ajax
{
///<summary>
/// $codebehindclassname$ 的摘要说明
///</summary>
[WebService(Namespace ="http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
publicclass Handler1 : IHttpHandler
{
publicvoid ProcessRequest(HttpContext context)
{
context.Response.ContentType ="text/plain";
//接收ajax请求的参数值
string name = context.Request["name"];
using (SqlConnection conn =new SqlConnection(ConfigurationManager.ConnectionStrings["learning"].ConnectionString))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText =string.Format("select username from Users where username='{0}'", name);
int i = cmd.ExecuteNonQuery();
if (i >1)
{
//返回提示信息
context.Response.Write("数据库存在重复数据");
}
if (i ==1)
{
context.Response.Write("此用户名以注册!");
}
context.Response.Write("恭喜你可以注册!");
}
}
}
publicbool IsReusable
{
get
{
returnfalse;
}
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
using System.Configuration;
namespace Ajax
{
///<summary>
/// $codebehindclassname$ 的摘要说明
///</summary>
[WebService(Namespace ="http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
publicclass Handler1 : IHttpHandler
{
publicvoid ProcessRequest(HttpContext context)
{
context.Response.ContentType ="text/plain";
//接收ajax请求的参数值
string name = context.Request["name"];
using (SqlConnection conn =new SqlConnection(ConfigurationManager.ConnectionStrings["learning"].ConnectionString))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText =string.Format("select username from Users where username='{0}'", name);
int i = cmd.ExecuteNonQuery();
if (i >1)
{
//返回提示信息
context.Response.Write("数据库存在重复数据");
}
if (i ==1)
{
context.Response.Write("此用户名以注册!");
}
context.Response.Write("恭喜你可以注册!");
}
}
}
publicbool IsReusable
{
get
{
returnfalse;
}
}
}
}
2,Ajax无刷新评论:
主要是用ajax将用户的评论信息返回到httphandler页面进行无刷新处理,存入数据库,之后再用Dom动态加载的形式将用户评论内容加载到页面,
这样就实现了无刷新评论功能
首先建立两个httphandler页面,一个“Global.asax”拼接显示已有评论信息,一个“todata.ashx”将心评论信息存入数据库并返回是否插入成功
Global.asax:
View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
using System.Configuration;
using System.Text;
namespace Ajax
{
///<summary>
/// $codebehindclassname$ 的摘要说明
///</summary>
[WebService(Namespace ="http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
publicclass GetData : IHttpHandler
{
publicvoid ProcessRequest(HttpContext context)
{
context.Response.ContentType ="text/plain";
StringBuilder bur =new StringBuilder();
//将原始评论信息逐行读取并以"|"分隔每列,以"$"分隔每行
using (SqlConnection conn =new SqlConnection(ConfigurationManager.ConnectionStrings["Learning"].ConnectionString))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText ="select * from T_post";
SqlDataReader reader= cmd.ExecuteReader();
while (reader.Read())
{
//将所有信息拼接起来
bur.Append(reader.GetSqlString(1)).Append("|").Append(reader.GetSqlString(2)).Append("|").Append(reader.GetSqlDateTime(3)).Append("$");
}
}
}
//将拼接起来的数据去掉最后一个"$"符号返回
context.Response.Write(bur.ToString().Trim('$'));
}
publicbool IsReusable
{
get
{
returnfalse;
}
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
using System.Configuration;
using System.Text;
namespace Ajax
{
///<summary>
/// $codebehindclassname$ 的摘要说明
///</summary>
[WebService(Namespace ="http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
publicclass GetData : IHttpHandler
{
publicvoid ProcessRequest(HttpContext context)
{
context.Response.ContentType ="text/plain";
StringBuilder bur =new StringBuilder();
//将原始评论信息逐行读取并以"|"分隔每列,以"$"分隔每行
using (SqlConnection conn =new SqlConnection(ConfigurationManager.ConnectionStrings["Learning"].ConnectionString))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText ="select * from T_post";
SqlDataReader reader= cmd.ExecuteReader();
while (reader.Read())
{
//将所有信息拼接起来
bur.Append(reader.GetSqlString(1)).Append("|").Append(reader.GetSqlString(2)).Append("|").Append(reader.GetSqlDateTime(3)).Append("$");
}
}
}
//将拼接起来的数据去掉最后一个"$"符号返回
context.Response.Write(bur.ToString().Trim('$'));
}
publicbool IsReusable
{
get
{
returnfalse;
}
}
}
}
todata.ashx:
View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
namespace Ajax
{
///<summary>
/// $codebehindclassname$ 的摘要说明
///</summary>
[WebService(Namespace ="http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
publicclass todata : IHttpHandler
{
publicvoid ProcessRequest(HttpContext context)
{
context.Response.ContentType ="text/plain";
//取得ajax返回的评论信息插入数据库
string mas = context.Request["msg"];
using (SqlConnection conn =new SqlConnection(ConfigurationManager.ConnectionStrings["Learning"].ConnectionString))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText =string.Format("insert into T_post(IpAdd,Msg,Date) values('{0}','{1}','{2}')", context.Request.UserHostAddress, mas, DateTime.Now);
int i = cmd.ExecuteNonQuery();
if (i >=0)
{
context.Response.Write("评论成功!");
}
else
{
context.Response.Write("评论失败,请重试!");
}
}
}
}
publicbool IsReusable
{
get
{
returnfalse;
}
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
namespace Ajax
{
///<summary>
/// $codebehindclassname$ 的摘要说明
///</summary>
[WebService(Namespace ="http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
publicclass todata : IHttpHandler
{
publicvoid ProcessRequest(HttpContext context)
{
context.Response.ContentType ="text/plain";
//取得ajax返回的评论信息插入数据库
string mas = context.Request["msg"];
using (SqlConnection conn =new SqlConnection(ConfigurationManager.ConnectionStrings["Learning"].ConnectionString))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText =string.Format("insert into T_post(IpAdd,Msg,Date) values('{0}','{1}','{2}')", context.Request.UserHostAddress, mas, DateTime.Now);
int i = cmd.ExecuteNonQuery();
if (i >=0)
{
context.Response.Write("评论成功!");
}
else
{
context.Response.Write("评论失败,请重试!");
}
}
}
}
publicbool IsReusable
{
get
{
returnfalse;
}
}
}
}
前台显示:
建立html静态页面
View Code
<!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></title>
<script src="js/jquery-1.4.2.js" type="text/javascript"></script>
<script type="text/javascript">
//用javascript显示ajax信息
//当按钮点击是用ajas将数据返回到httphandler页面进行处理
function sa() {
var ms = document.getElementById("TextArea1").value;
var Xmlhttp =new ActiveXObject("Microsoft.XMLHTTP");
if (!Xmlhttp) {
alert("http异常");
return;
}
Xmlhttp.open("POST", "todata.ashx?msg="+ encodeURI(ms), false);
Xmlhttp.onreadystatechange = function() {
if (Xmlhttp.readyState ==4) {
if (Xmlhttp.status ==200) {////状态码是200则成功
//将成功信息返回到ajax显示
alert(Xmlhttp.responseText);
//javascript添加
// var li = document.createElement("li");
// li.innerText = "IP地址是:127.0.0.1" + "内容是:" + ms + "发布日期:" + new Date();
// document.getElementById("comm").appendChild(li);
//// //jquery添加我建议用jquery添加,
//动态拼接显示用户信息
var child ="<li>IP地址是:127.0.0.1"+"内容是:"+ ms +"发布日期:"+new Date() +"</li>"
$("#comm").append(child);
}
else {
alert("ajax错误!");
}
}
}
Xmlhttp.send();
}
//用jquery显示ajax信息
//当页面加载时动态的将数据库信息从GetData.ashx拼接好返回到ajax动态加载显示
$(function() {
$.post("GetData.ashx", function(data, status) {
//data为返回的数据,status为ajax的请求状态,success为ajax成功
if (status !="success") {
$("#comm").appand("<li>加载失败</li>");
return;
}
//因为从数据库读取是已经将每行数据以"$"分隔。将每列数据一"|"分隔
//将数据一"$"分隔遍历每行
var lines = data.split("$");
for (var i =0; i < lines.length; i++) {
//将每行数据一"|"分隔遍历每列
var line = lines[i];
var filed = line.split("|");
//拼接显示
var commen = $("<li>IP地址是:"+ filed[0] +"内容是:"+ filed[1] +"发布日期:"+ filed[2] +"</li>");
$("#comm").append(commen);
}
});
});
</script>
<style type="text/css">
#TextArea1
{
width: 316px;
height: 87px;
}
#Button1
{
width: 70px;
}
</style>
</head>
<body>
<ul id="comm">
</ul>
<p>
<textarea id="TextArea1" name="S1"></textarea></p>
<p>
<input id="Button1" type="button" value="评论" onclick="sa()"/></p>
</body>
</html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="js/jquery-1.4.2.js" type="text/javascript"></script>
<script type="text/javascript">
//用javascript显示ajax信息
//当按钮点击是用ajas将数据返回到httphandler页面进行处理
function sa() {
var ms = document.getElementById("TextArea1").value;
var Xmlhttp =new ActiveXObject("Microsoft.XMLHTTP");
if (!Xmlhttp) {
alert("http异常");
return;
}
Xmlhttp.open("POST", "todata.ashx?msg="+ encodeURI(ms), false);
Xmlhttp.onreadystatechange = function() {
if (Xmlhttp.readyState ==4) {
if (Xmlhttp.status ==200) {////状态码是200则成功
//将成功信息返回到ajax显示
alert(Xmlhttp.responseText);
//javascript添加
// var li = document.createElement("li");
// li.innerText = "IP地址是:127.0.0.1" + "内容是:" + ms + "发布日期:" + new Date();
// document.getElementById("comm").appendChild(li);
//// //jquery添加我建议用jquery添加,
//动态拼接显示用户信息
var child ="<li>IP地址是:127.0.0.1"+"内容是:"+ ms +"发布日期:"+new Date() +"</li>"
$("#comm").append(child);
}
else {
alert("ajax错误!");
}
}
}
Xmlhttp.send();
}
//用jquery显示ajax信息
//当页面加载时动态的将数据库信息从GetData.ashx拼接好返回到ajax动态加载显示
$(function() {
$.post("GetData.ashx", function(data, status) {
//data为返回的数据,status为ajax的请求状态,success为ajax成功
if (status !="success") {
$("#comm").appand("<li>加载失败</li>");
return;
}
//因为从数据库读取是已经将每行数据以"$"分隔。将每列数据一"|"分隔
//将数据一"$"分隔遍历每行
var lines = data.split("$");
for (var i =0; i < lines.length; i++) {
//将每行数据一"|"分隔遍历每列
var line = lines[i];
var filed = line.split("|");
//拼接显示
var commen = $("<li>IP地址是:"+ filed[0] +"内容是:"+ filed[1] +"发布日期:"+ filed[2] +"</li>");
$("#comm").append(commen);
}
});
});
</script>
<style type="text/css">
#TextArea1
{
width: 316px;
height: 87px;
}
#Button1
{
width: 70px;
}
</style>
</head>
<body>
<ul id="comm">
</ul>
<p>
<textarea id="TextArea1" name="S1"></textarea></p>
<p>
<input id="Button1" type="button" value="评论" onclick="sa()"/></p>
</body>
</html>
3,前台ajax想服务器端返回xml对象,服务器端接收处理,并且想ajax返回处理后的xml
好处是数据量没有限制,而且安全
前台:
View Code
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AjaxXml.aspx.cs" Inherits="注册.AjaxXml"%>
<!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">
function Load() {
//创建xml
sXML ="<?xml version=\"1.0\" encoding=\"gb2312\" ?>";
sXML +="<Info>";
sXML +="<kcid>11</kcid>";
sXML +="<ksfs>0</ksfs>";
sXML +="<tgfs>0</tgfs>";
sXML +="<kspd>zy</kspd>";
sXML +="</Info>";
//创建xmldocument对象
xmlDocument =new ActiveXObject("Msxml2.DOMDocument");
xmlDocument.async =false;
//将创建的xml加入到xmldocument中
xmlDocument.loadXML(sXML);
//=========================================================
//定义xmlhttp协议
var XmlHTTP =new ActiveXObject("Microsoft.XMLHTTP");
if (!XmlHTTP) {
alert("ajax异常!");
returnfalse;
}
//发送
XmlHTTP.open("POST", "Handler2.ashx", false);
XmlHTTP.onreadystatechange = function() {
if (XmlHTTP.readyState ==4) {
if (XmlHTTP.status ==200) {
//如果发送成功,则接收服务端返回的xml对象,首先定义xmldom协议
xdDoc =new ActiveXObject("Microsoft.XMLDOM");
xdDoc.async =false;
//将返回的xml加载到对象中
xdDoc.loadXML(XmlHTTP.ResponseText);
//获取返回对象getip节点的值
var x = xdDoc.getElementsByTagName("getIp")[0].childNodes[0].nodeValue;
alert(x);
}
else {
alert("ajax错误");
}
}
}
//将xmldocument对象发送到服务端
XmlHTTP.send(xmlDocument);
}
</script>
</head>
<body onload="Load()">
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
<!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">
function Load() {
//创建xml
sXML ="<?xml version=\"1.0\" encoding=\"gb2312\" ?>";
sXML +="<Info>";
sXML +="<kcid>11</kcid>";
sXML +="<ksfs>0</ksfs>";
sXML +="<tgfs>0</tgfs>";
sXML +="<kspd>zy</kspd>";
sXML +="</Info>";
//创建xmldocument对象
xmlDocument =new ActiveXObject("Msxml2.DOMDocument");
xmlDocument.async =false;
//将创建的xml加入到xmldocument中
xmlDocument.loadXML(sXML);
//=========================================================
//定义xmlhttp协议
var XmlHTTP =new ActiveXObject("Microsoft.XMLHTTP");
if (!XmlHTTP) {
alert("ajax异常!");
returnfalse;
}
//发送
XmlHTTP.open("POST", "Handler2.ashx", false);
XmlHTTP.onreadystatechange = function() {
if (XmlHTTP.readyState ==4) {
if (XmlHTTP.status ==200) {
//如果发送成功,则接收服务端返回的xml对象,首先定义xmldom协议
xdDoc =new ActiveXObject("Microsoft.XMLDOM");
xdDoc.async =false;
//将返回的xml加载到对象中
xdDoc.loadXML(XmlHTTP.ResponseText);
//获取返回对象getip节点的值
var x = xdDoc.getElementsByTagName("getIp")[0].childNodes[0].nodeValue;
alert(x);
}
else {
alert("ajax错误");
}
}
}
//将xmldocument对象发送到服务端
XmlHTTP.send(xmlDocument);
}
</script>
</head>
<body onload="Load()">
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
服务器端:
View Code
using System;
using System.Collections;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.IO;
using System.Xml;
namespace 注册
{
///<summary>
/// $codebehindclassname$ 的摘要说明
///</summary>
[WebService(Namespace ="http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
publicclass Handler2 : IHttpHandler
{
publicvoid ProcessRequest(HttpContext context)
{
context.Response.ContentType ="text/plain";
string ip ="";
try
{
context.Response.Write("<?xml version='1.0' encoding='gb2312' ?>");
context.Response.Write("<getIp>");
////////////////////处理从ajax返回的Xml,此处没用///////////////////////////////
//定义xml对象
XmlDocument xmlDoc =new XmlDocument();
// 接收前台返回的xml对象
xmlDoc.Load(context.Request.InputStream);
//将xml对象转换为io流(注:必须)
StringReader reader =new StringReader(xmlDoc.InnerXml.ToString());
DataSet ds =new DataSet();
//将io流加入DataSet
ds.ReadXml(reader);
//获取返回的xml中kspd的值
ip = ds.Tables[0].Rows[0]["kspd"].ToString();
///////////////////////////////////////////////////////////
context.Response.Write(ip);
context.Response.Write("</getIp>");
}
catch
{
context.Response.Write("<?xml version='1.0' encoding='gb2312' ?>");
context.Response.Write("<getIp>");
context.Response.Write("大哥,我错了!哈哈哈!");
context.Response.Write("</getIp>");
}
}
publicbool IsReusable
{
get
{
returnfalse;
}
}
}
}
using System.Collections;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.IO;
using System.Xml;
namespace 注册
{
///<summary>
/// $codebehindclassname$ 的摘要说明
///</summary>
[WebService(Namespace ="http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
publicclass Handler2 : IHttpHandler
{
publicvoid ProcessRequest(HttpContext context)
{
context.Response.ContentType ="text/plain";
string ip ="";
try
{
context.Response.Write("<?xml version='1.0' encoding='gb2312' ?>");
context.Response.Write("<getIp>");
////////////////////处理从ajax返回的Xml,此处没用///////////////////////////////
//定义xml对象
XmlDocument xmlDoc =new XmlDocument();
// 接收前台返回的xml对象
xmlDoc.Load(context.Request.InputStream);
//将xml对象转换为io流(注:必须)
StringReader reader =new StringReader(xmlDoc.InnerXml.ToString());
DataSet ds =new DataSet();
//将io流加入DataSet
ds.ReadXml(reader);
//获取返回的xml中kspd的值
ip = ds.Tables[0].Rows[0]["kspd"].ToString();
///////////////////////////////////////////////////////////
context.Response.Write(ip);
context.Response.Write("</getIp>");
}
catch
{
context.Response.Write("<?xml version='1.0' encoding='gb2312' ?>");
context.Response.Write("<getIp>");
context.Response.Write("大哥,我错了!哈哈哈!");
context.Response.Write("</getIp>");
}
}
publicbool IsReusable
{
get
{
returnfalse;
}
}
}
}