给你一个轻量级的ajax框架: function XHConn() { var xmlhttp, bComplete = false; try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { try { xmlhttp = new XMLHttpRequest(); } catch (e) { xmlhttp = false; }}} if (!xmlhttp) return null; this.connect = function(sURL, sMethod, sVars, fnDone) { if (!xmlhttp) return false; bComplete = false; sMethod = sMethod.toUpperCase(); try { if (sMethod == "GET") { xmlhttp.open(sMethod, sURL+"?"+sVars, true); sVars = ""; } else { xmlhttp.open(sMethod, sURL, true); xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1"); xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); } xmlhttp.onreadystatechange = function(){ if (xmlhttp.readyState == 4 && xmlhttp.status == 200 && !bComplete) { bComplete = true; fnDone(xmlhttp); }}; xmlhttp.send(sVars); } catch(z) { return false; } return true; }; return this; }Usage XHConn is a data object with a single method. In order to use the object, you must first instantiate a copy of it.var myConn = new XHConn();After instantiating the object, it is good practice to check for success and act accordingly.if (!myConn) // XMLHTTP not available. exit method/handle error.After you know you have a valid connection to work with, you need to define a function that will fire after your connection is complete. Your function should take a single argument which will be the XMLHttpRequest object with its members intact. [see: XMLHTTPRequest members]var fnWhenDone = function (oXML) { alert(oXML.responseText); };Then the final step is to make your actual connection using the connect member function of the XHConn object. The method takes the following arguments: sURL - String - The string that specifies the path to the resource to connect to. (Note: Cross-domain scripting is explicitly denied with XMLHTTP for security reasons. You may only access files within the same domain as the host file.) sMethod - String - One of either "GET" or "POST", which specify the type of HTTP request to make. sVars - String - A string of arguments, encoded in the form var1=val1&var2=val2&.... These are the variables that will be submitted along with the request. fnDone - Function - A reference to a function that will be called upon completion of the HTTP request. A single argument, the XMLHTTPRequest object, will be passed to the function. So a typical function call would look something like this:myConn.connect("mypage.php", "POST", "foo=bar&baz=qux", fnWhenDone);At this point your connection will be made and the results will be sent to your function. The two major members of the XMLHTTPRequest object that you will deal with are responseText and responseXML.
document.getElementById("lblTitle").innerText=http_request.responseText; } } } </script>//创建一般处理程序 using System; using System.Web;public class Handler : IHttpHandler { DB DBManager = new DB();
public void ProcessRequest (HttpContext context) { context.Response.ContentType = "text/plain";
string flag = context.Request.QueryString["flag"].ToString(); if (flag.Equals("addAdmin")) { string userName = context.Request.QueryString["userName"].ToString(); string strSql = "select count(*) from admin where userName = '" + userName + "'"; if (Convert.ToInt32(DBManager.executeGetReturn(strSql)) > 0) { context.Response.Write("该用户已经存在"); } else { context.Response.Write("你可以注册[" + userName + "]"); } } else if (flag.Equals("updateTitle")) { int id = Convert.ToInt32(context.Request.QueryString["id"].ToString()); string strSql = "update voteConfig set id=" + id; if (DBManager.executeNonQuery(strSql) > 0) { context.Response.Write("设置已成功,当前系统前调查[" + DBManager.executeGetReturn("select voteTitle from voteMaster where id=" + id) + "]"); } else { context.Response.Write("设置失败"); } } } public bool IsReusable { get { return false; } }}
<html>
<head>
<script language="javascript" type="text/javascript">
function getXMLRequester()
{ var xmlhttp_request = false;
try
{ if( window.ActiveXObject )
{ for( var i = 5; i; i-- ){
try{
if( i == 2 )
{ xmlhttp_request = new ActiveXObject( "Microsoft.XMLHTTP" ); }
else
{ xmlhttp_request = new ActiveXObject
( "Msxml2.XMLHTTP." + i + ".0" );
xmlhttp_request.setRequestHeader("Content-Type","text/xml");
xmlhttp_request.setRequestHeader("Content-Type","gb2312"); }
break;}
catch(e){ xmlhttp_request = false; } } }
else if( window.XMLHttpRequest )
{ xmlhttp_request = new XMLHttpRequest();
if (xmlhttp_request.overrideMimeType)
{ xmlhttp_request.overrideMimeType("text/xml"); } } }
catch(e){ xmlhttp_request = false; }
return xmlhttp_request ; }
function IDRequest(n){
url=n+document.getElementById("163id").value;
alert(url);
xmlhttp_request=getXMLRequester();
xmlhttp_request.onreadystatechange = doContents;//iupdoContentso?Eo
xmlhttp_request.open("GET", url, true);
xmlhttp_request.send(null);
}
function doContents()
{ if (xmlhttp_request.readyState == 4) {
if (xmlhttp_request.status == 200) {
//alert(xmlhttp_request.responseText);
document.getElementById("message").innerHTML = xmlhttp_request.responseText;
}
else { alert("bad!"); } } }
</script>
</head>
<body>
<input type="text" id="163id" onchange="IDRequest('http://reg.163.com/register/checkssn.jsp?username=')"/><span id="message"></span>
<!--
<button id="button1" onclick="IDRequest('http://reg.163.com/register/checkssn.jsp?username=')">button</button>
--></body>
</html>以上的http://reg.163.com/register/checkssn.jsp为163的验证用页面,返回用户名认证信息。仅供参考。
function checkusername()
{
var username=$("loginid");
var strname=username.value;
if(trim(strname)!='')
{
if(strname.length<4||strname.length>20 )
{
showMsgErr("loginid_info","用户ID的字符数不能小于4和大于20!");
pass=false;
usernamepass=false;
return false;
}
if(!validatestr(strname))
{
showMsgErr("loginid_info","用户ID只能由数字和字母组成!");
pass=false;
usernamepass=false;
return false;
}
showMsgWarm("loginid_info","检测中,请稍等...");
hotelmember.isExistUser(strname,
function(result){
if(result.value)
{
showMsgErr("loginid_info","该用户名已存在!");
pass=false;
usernamepass=false;
return false;
}
else
{
usernamepass=true;
showMsgOk("loginid_info","该用户名可以注册!");
}
}
);
}
else
{
$("loginid_info").style.display="none";
pass=false;
usernamepass=false;
} }//------判断输入是否为 以字母开头的字符串,由字母和数字组成------//
function validatestr(str1){
var str = str1;
var patn =/^[a-zA-Z]+[a-zA-Z0-9]+$/;
if(!patn.test(str)){
return false;
}
return true;
}</script>
用户名输入框:
<input id="loginid" maxLength="20" size="32" name="username" runat="server" onfocus="javascript:title1('loginid','loginid_info','由4-20个字母或数字组成。不支持中文,不能以数字开头,注册成功后不可修改。');" onblur="javascript:checkusername();" />
CS文件中进行检测:
public bool isExistUser(string UserName)
{
bool flag = MemberUtils.Exists("Where UserName='" + UserName + "'"); return flag;
}
<input id="loginid" maxLength="20" size="32" name="username" runat="server" onblur="javascript:checkusername(this.value);" />
</div>后台:
public bool isExistUser(string UserName)
{
string strConnection = System.Configuration.ConfigurationManager.AppSettings["connectionsqlserver"];
SqlConnection objConn = new SqlConnection(strConnection);
string strsql = "select 用户名 from users where 用户名=@UserName";
objConn.Open();
SqlCommand dbComm = new SqlCommand(strsql, objConn);
dbComm.Parameters.Add("@UserName", SqlDbType.VarChar, 50);
dbComm.Parameters["@UserName"].Value = UserName;
string lookupPassword = dbComm.ExecuteScalar().ToString();
objConn.Close();
if (lookupPassword=="") return false;
else return true;
}
但是 在checksum里无法调用isExistUser是怎么回事?
<script type="text/javascript">
function checkusername(aa)
{
isExistUser(aa);//无法调用,
}
</script>
运行离开焦点显示网页有错误
$(document).ready(function(){
//传说中的ready加载方法.效率比window.load高很多.IE兼容性也非常好
//给input绑定onblur事件
$("#userEmail").blur(function(){
checkEmail(this);
});
});
//判断Email合法性
var checkEmail = function(obj)
{
if(obj.value.replace(/ /g,'') == "")
{
//做一些提示用户处理
$("#msgEmail").html("请输入Email").show();
$("#checkEmailExists").hide();
return true;
}
if((/^[a-z0-9A-z_]+@[a-z0-9A-z]+.[a-z0-9A-Z]+$/).test(obj.value))
{
//做一些提示用户处理
$("#msgEmail").html("").hide();
$("#checkEmailExists").show();
return true;
}
$("#msgEmail").html("Email错误,请正确输入").show();
$("#checkEmailExists").hide();
return false;
}//在通过Email合法性后 ajax传输参数到后台进行指定的操作 并返回相映的值
$.ajax({
type: "POST",
url: "Servers/CheckEmailSever.aspx",//处理数据的页面
data: "mode=U_Name&url="+ $("#userEmail").val(),//参数
success: function(msg){//msg返回值0 or 1 这个自己拟订
if(msg==0)? 成功:失败;
}在$("#userEmail").val() 输入时,应对用户输入的枝进行判断是否合法.后台就没必要说了吧!
1.接收参数.
2.参数处理,防注入.
3.SQL查询是否存在.
4.返回相映的值 JS做提示处理.
http://blog.csdn.net/lem12/archive/2007/04/10/1558947.aspx
sql server行不行?
response.contentType="text/xml";
response.write("<xml><result><id>1</id></result>");
return;后台是php文件也是一样,设置输出类型为xml
echo ("<xml><result><id>1</id></result>");
return;
<input type="text" id="loginid" maxLength="20" size="32" name="username" onblur="AjaxCheckUserName(this)">var AjaxCheckUserName=function(el)
{
if(el.value!="")
{发送Ajax调用;
}
}
前台只需要把用户输入的用户名传过来就行了
如果用户不多的话,建议试用数据库CACHE
function XHConn()
{
var xmlhttp, bComplete = false;
try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) { try { xmlhttp = new XMLHttpRequest(); }
catch (e) { xmlhttp = false; }}}
if (!xmlhttp) return null;
this.connect = function(sURL, sMethod, sVars, fnDone)
{
if (!xmlhttp) return false;
bComplete = false;
sMethod = sMethod.toUpperCase(); try {
if (sMethod == "GET")
{
xmlhttp.open(sMethod, sURL+"?"+sVars, true);
sVars = "";
}
else
{
xmlhttp.open(sMethod, sURL, true);
xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200 && !bComplete)
{
bComplete = true;
fnDone(xmlhttp);
}};
xmlhttp.send(sVars);
}
catch(z) { return false; }
return true;
};
return this;
}Usage
XHConn is a data object with a single method. In order to use the object, you must first instantiate a copy of it.var myConn = new XHConn();After instantiating the object, it is good practice to check for success and act accordingly.if (!myConn) // XMLHTTP not available. exit method/handle error.After you know you have a valid connection to work with, you need to define a function that will fire after your connection is complete. Your function should take a single argument which will be the XMLHttpRequest object with its members intact. [see: XMLHTTPRequest members]var fnWhenDone = function (oXML) { alert(oXML.responseText); };Then the final step is to make your actual connection using the connect member function of the XHConn object. The method takes the following arguments: sURL - String - The string that specifies the path to the resource to connect to. (Note: Cross-domain scripting is explicitly denied with XMLHTTP for security reasons. You may only access files within the same domain as the host file.)
sMethod - String - One of either "GET" or "POST", which specify the type of HTTP request to make.
sVars - String - A string of arguments, encoded in the form var1=val1&var2=val2&.... These are the variables that will be submitted along with the request.
fnDone - Function - A reference to a function that will be called upon completion of the HTTP request. A single argument, the XMLHTTPRequest object, will be passed to the function. So a typical function call would look something like this:myConn.connect("mypage.php", "POST", "foo=bar&baz=qux", fnWhenDone);At this point your connection will be made and the results will be sent to your function. The two major members of the XMLHTTPRequest object that you will deal with are responseText and responseXML.
<asp:TextBox ID="txtUserName" runat="server" onBlur="send_request('addAdmin');"></asp:TextBox>
//script处理函数 <script language="javascript" type="text/javascript">
function send_request(flag)
{
//创建XMLHttpRequest;
http_request = false;
if(window.XMLHttpRequest)
{
// 非IE 浏览器
http_request = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
//IE
try
{
http_request = new ActiveXObject("Msxml2.XMLHTTP");//较新版本的IE
}catch(e)
{
try
{
http_request = new ActiveXOBject("Microsoft.XMLHTTP");//旧版本IE
}catch(e){}
}
}
else
{
window.alert("不能创建 XMLHttpRequest对象,无法应用Ajax");
return false;
}
//指定回调函数
if(flag == "addAdmin")
{
http_request.onreadystatechange = addAdmin;
//创建HTTP请求
http_request.open("get","Handler.ashx?flag=addAdmin&userName="+document.getElementById("txtUserName").value,true);
}
else if(flag == "updateTitle")
{
http_request.onreadystatechange = updateTitle;
//创建HTTP请求
i = document.getElementById("ddlVoteTitle").selectedIndex;//选择的索引
id = document.form1.ddlVoteTitle.options[i].value;
http_request.open("get","Handler.ashx?flag=updateTitle&id="+id,true);
}
//发送上面创建的HTTP请求
http_request.send(null);
}
function addAdmin()
{
if(http_request.readyState == 4)
{
if(http_request.status == 200)
{
//正式处理有信息
if(http_request.responseText == "该用户已经存在")
{
//隐藏提交按扭
document.getElementById("Button1").style.display ="none";
}
else
{
document.getElementById("Button1").style.display="";
}
document.getElementById("lblShow").innerText=http_request.responseText;
}
}
}
function updateTitle()
{
if(http_request.readyState == 4) {
if(http_request.status == 200)
{
//正式处理有信息
document.getElementById("lblTitle").innerText=http_request.responseText;
}
}
}
</script>//创建一般处理程序
using System;
using System.Web;public class Handler : IHttpHandler { DB DBManager = new DB();
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
string flag = context.Request.QueryString["flag"].ToString(); if (flag.Equals("addAdmin"))
{ string userName = context.Request.QueryString["userName"].ToString();
string strSql = "select count(*) from admin where userName = '" + userName + "'"; if (Convert.ToInt32(DBManager.executeGetReturn(strSql)) > 0)
{
context.Response.Write("该用户已经存在");
}
else
{
context.Response.Write("你可以注册[" + userName + "]");
}
}
else if (flag.Equals("updateTitle"))
{
int id = Convert.ToInt32(context.Request.QueryString["id"].ToString());
string strSql = "update voteConfig set id=" + id;
if (DBManager.executeNonQuery(strSql) > 0)
{
context.Response.Write("设置已成功,当前系统前调查[" + DBManager.executeGetReturn("select voteTitle from voteMaster where id=" + id) + "]");
}
else
{
context.Response.Write("设置失败");
}
}
} public bool IsReusable {
get {
return false;
}
}}