初识Ajax技术2

本文介绍如何利用Ajax技术实现在用户输入用户名时实时检查用户名是否已被占用,避免页面刷新,提高用户体验。通过创建XMLHttpRequest对象进行后台数据交互,展示具体的JavaScript与C#代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >




 实现注册界面无刷新判断重名,由于要访问数据库,所以要达到无刷新,只能用Ajax技术。

 其中最重要的就是xmlHttp对象。

 

XmlHttp是什么?

最通用的定义为:XmlHttp是一套可以在Javascript、VbScript、Jscript等脚本语言中通过http协议传送或从接收XML及其他数据的一套API。XmlHttp最大的用处是可以更新网页的部分内容而不需要刷新整个页面。

来自MSDN的解释:XmlHttp提供客户端同http服务器通讯的协议。客户端可以通过XmlHttp对象(MSXML2.XMLHTTP.3.0)向http服务器发送请求并使用微软XML文档对象模型Microsoft® XML Document Object Model (DOM)处理回应。

现在的绝对多数浏览器都增加了对XmlHttp的支持,IE中使用ActiveXObject方式创建XmlHttp对象,其他浏览器如:Firefox、Opera等通过window.XMLHttpRequest来创建xmlhttp对象。

 

 在操作页的前台代码中 <input  ID="tbUserName" type="text"   onblur ="tbUserName_onBlue(this.value)">

 使用html文本框,即客户端控件 触发他的onblur事件调用js函数。

 

 在js文件中定义该函数

 

[javascript]  view plain copy print ?
  1. // JavaScript Document  
  2.   
  3. var xmlHttp;//全局XMLHttpResquest对象  
  4.   
  5. //针对不同浏览器,获取XMLHttpRequest对象  
  6. function CreateXMLHttpRequest()  
  7. {  
  8.     if(window.ActiveXObject)  
  9.     {  
  10.         xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");  
  11.     }  
  12.     else  
  13.     {  
  14.         xmlHttp=new XMLHttpResquest();  
  15.     }  
  16. }  
  17.   
  18. //离开tbUserName时调用的JS函数  
  19. function tbUserName_onBlue(name)  
  20. {  
  21.     //创建XMLHTTPRquest对象  
  22.     CreateXMLHttpRequest();  
  23.       
  24.     //指定回调函数  
  25.     xmlHttp.onreadystatechange=HandleStateChange;  
  26.       
  27.     //打开请求  
  28.     xmlHttp.open("GET","ForAjax.aspx?name=" + name,true);  
  29.       
  30.     //发送请求  
  31.     xmlHttp.send(null);  
  32.       
  33. }  
  34.   
  35. //回调函数  
  36. function HandleStateChange()  
  37. {  
  38.       
  39.     if(xmlHttp.readyState==4)  //返回当前请求的状态,只读  
  40.     {  
  41.         if(xmlHttp.status==200) //返回当前请求的http状态码.只读  
  42.         {  
  43.              //responseText为接收服务器发过来的值  
  44.                
  45.            if(xmlHttp.responseText=="wrong1")  
  46.            {  
  47.            document.getElementById("sp1").innerText ="用户名不能为空!";  
  48.            document.getElementById("img1").src="image/wrong.jpg";  
  49.            }  
  50.            else if(xmlHttp.responseText=="wrong2")  
  51.            {  
  52.            document.getElementById("sp1").innerText="用户名重名!";  
  53.            document.getElementById("img1").src="image/wrong.jpg";  
  54.            }  
  55.            else if(xmlHttp.responseText=="right")  
  56.            {  
  57.             document.getElementById("sp1").innerText="正确,可以注册!";  
  58.             document.getElementById("img1").src="image/right.jpg"  
  59.            }  
  60.         }  
  61.     }  
  62. }  

 

 然后再创建一个web页面文件(我把他命名为ForAjax.aspx),在他的cs文件中通过Response.Write()返回值赋给js文件中的xmlHttp对象的responseText属性 (xmlHttp.responseText)。ForAjax.aspx不显示,只做某种操作以返回值达到某种需求。可以说是一个幕后英雄。

ForAjax.aspx.cs文件代码:

[c-sharp]  view plain copy print ?
  1. using System;  
  2. using System.Collections;  
  3. using System.Configuration;  
  4. using System.Data;  
  5. using System.Linq;  
  6. using System.Web;  
  7. using System.Web.Security;  
  8. using System.Web.UI;  
  9. using System.Web.UI.HtmlControls;  
  10. using System.Web.UI.WebControls;  
  11. using System.Web.UI.WebControls.WebParts;  
  12. using System.Xml.Linq;  
  13.   
  14. public partial class ForAjax : System.Web.UI.Page  
  15. {  
  16.     protected void Page_Load(object sender, EventArgs e)  
  17.     {  
  18.         string name = Request.QueryString["name"].ToString(); //读出name的值  
  19.           
  20.         
  21.         string strQry = @"select * from UserList where UserName='" + name + "'";  
  22.         SqlHelper helper = new SqlHelper(@"Data Source=A102-35/SQLEXPRESS;DataBase=DB_Login;Integrated Security=true");  
  23.   
  24.         if (name=="")  
  25.         {  
  26.             Response.Clear();               //清空缓冲区  
  27.             Response.Write("wrong1");       //写操作,返回值给xmlHttp.responseText  
  28.             Response.End();                 //结束写入数据流  
  29.         }  
  30.         else if (helper.RunReader(strQry).Read())  
  31.         {  
  32.             Response.Clear();  
  33.             Response.Write("wrong2");  
  34.             Response.End();  
  35.         }  
  36.         else  
  37.         {  
  38.             Response.Clear();  
  39.             Response.Write("right");  
  40.             Response.End();  
  41.         }  
  42.   
  43.     }  
  44. }  

 

 

XmlHttp对象参考:

属性:

onreadystatechange*指定当readyState属性改变时的事件处理句柄。只写
readyState返回当前请求的状态,只读.
responseBody将回应信息正文以unsigned byte数组形式返回.只读
responseStream以Ado Stream对象的形式返回响应信息。只读
responseText将响应信息作为字符串返回.只读
responseXML将响应信息格式化为Xml Document对象并返回,只读
status返回当前请求的http状态码.只读
statusText返回当前请求的响应行状态,只读

* 表示此属性是W3C文档对象模型的扩展.

方法:

abort取消当前请求
getAllResponseHeaders获取响应的所有http头
getResponseHeader从响应信息中获取指定的http头
open创建一个新的http请求,并指定此请求的方法、URL以及验证信息(用户名/密码)
send发送请求到http服务器并接收回应
setRequestHeader单独指定请求的某个http头

事件:无

 -----------------------------------------------------------------------------------------------------------------------

readyState属性

变量,此属性只读,状态用长度为4的整型表示.定义如下:

0 (未初始化)对象已建立,但是尚未初始化(尚未调用open方法)
1 (初始化)对象已建立,尚未调用send方法
2 (发送数据)send方法已调用,但是当前的状态及http头未知
3 (数据传送中)已接收部分数据,因为响应及http头不全,这时通过responseBody和responseText获取部分数据会出现错误,
4 (完成)数据接收完毕,此时可以通过通过responseBody(为为解码的二进制数据)和responseText获取完整的回应数据

 

-----------------------------------------------------------------------------------------------------------------------

status属性

返回当前请求的http状态码

长整形标准http状态码,定义如下:

NumberDescription

100

Continue

101

Switching protocols

200

OK

201

Created

202

Accepted

203

Non-Authoritative Information

204

No Content

205

Reset Content

206

Partial Content

300

Multiple Choices

301

Moved Permanently

302

Found

303

See Other

304

Not Modified

305

Use Proxy

307

Temporary Redirect

400

Bad Request

401

Unauthorized

402

Payment Required

403

Forbidden

404

Not Found

405

Method Not Allowed

406

Not Acceptable

407

Proxy Authentication Required

408

Request Timeout

409

Conflict

410

Gone

411

Length Required

412

Precondition Failed

413

Request Entity Too Large

414

Request-URI Too Long

415

Unsupported Media Type

416

Requested Range Not Suitable

417

Expectation Failed

500

Internal Server Error

501

Not Implemented

502

Bad Gateway

503

Service Unavailable

504

Gateway Timeout

505

HTTP Version Not Supported

备注

长整形,此属性只读,返回当前请求的http状态码,此属性仅当数据发送并接收完毕后才可获取。

 

-----------------------------------------------------------------------------------------------------------------------

onreadystatechange属性

指定当readyState属性改变时的事件处理句柄

当XMLHTTPRequest对象的readyState属性改变时调用HandleStateChange函数,当数据接收完毕后(readystate == 4)此页面上的一个按钮将被激活

[javascript]  view plain copy print ?
  1. var xmlhttp=null;  
  2. function PostOrder(xmldoc)  
  3. {  
  4.   var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP.5.0");  
  5.   xmlhttp.Open("POST""http://myserver/orders/processorder.asp"false);   
  6.   xmlhttp.onreadystatechange= HandleStateChange;  
  7.   xmlhttp.Send(xmldoc);  
  8.   myButton.disabled = true;  
  9. }  
  10. function HandleStateChange()  
  11. {  
  12.   if (xmlhttp.readyState == 4)  
  13.   {  
  14.     myButton.disabled = false;  
  15.     alert("Result = " + xmlhttp.responseXML.xml);  
  16.   }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值