ajax学习笔记(二)——AJAX详解

第一篇,理解了ajax是个什么东西,现在我们来好好探索一下它吧!

先发一个我自己做的小程序(简易百度搜索),我们再来一步步理解它:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script type="text/javascript">
        var xmlHttp=false;
        /*@cc_on @*/
        /*@if(@_jscript_version >= 5)
        try{
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }catch(e){
            try{
                xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
            }catch(e){
                xmlHttp=false;
            }
        }   
        @end @*/
        if(!xmlHttp && typeof XMLHttpRequest != 'undefined'){
            xmlHttp=new XMLHttpRequest();
        }
        function callServer(){
            var result=document.getElementById("Search").value;
            if(result=="" || result==null) return;
            var url="documentproc/processing1.ashx?key="+escape(result);
            xmlHttp.open("GET",url,true);
            xmlHttp.onreadystatechange=updatePage;
            xmlHttp.send(null);
            
        }
        
        function updatePage(){
            if(xmlHttp.readyState==1){
                document.getElementById("stateStr").innerHTML="正在加载文章对象……";
            }
            if(xmlHttp.readyState==2){
                document.getElementById("stateStr").innerHTML="连接对象加载完毕!";
            }
            if(xmlHttp.readyState==3){
                document.getElementById("stateStr").innerHTML="数据获取中,请稍后……";
            }
            if(xmlHttp.readyState==4){
                if (xmlHttp.status==200){
                    var result=xmlHttp.responseText.split("_");
                    document.getElementById("stateStr").innerHTML=result[0];
                }
                else if (xmlHttp.status == 404){
                    document.getElementById("stateStr").innerHTML="Request URL does not exist,发送的地址错了,没有此页面";
                }
                else if (xmlHttp.status == 403){
                    document.getElementById("stateStr").innerHTML="Access denied.无权访问";   
                }
                else{ 
                    document.getElementById("stateStr").innerHTML="Error: status code is " + xmlhttp.status;
                }
            }
        }
    </script>
    <title>无标题页</title>
</head>
<body>
    <input id="Search" type="text" style="width: 200px;" οnkeyup="callServer();"/><span style=" font-size:12px; color:Red">*请输入字母a-e</span>
    </br>
    <span id="stateStr" style=" background-color:Yellow; color:Black;"></span>
</body>
</html>

附加:后台处理文件processing1.ashx

View Code
<%@ WebHandler Language="C#" Class="processing1" %>

using System;
using System.Web;

public class processing1 : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/html";
        string val=context.Request.QueryString["key"].ToString();
        switch (val)
        {
            case "a":
                context.Response.Write("阿童木_阿呆");
                break;
            case "b":
                context.Response.Write("不要啊_不行");
                break;
            case "c":
                context.Response.Write("维生素c_c的果冻");
                break;
            case "d":
                context.Response.Write("冻结_懂了");
                break;
            case "dj":
                context.Response.Write("董娇娇_大家");
                break;
            case "e":
                context.Response.Write("额_厄运");
                break;
            default:
                context.Response.Write("无查询结果!");
                break;
        }
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

解剖开始喽……

1、首先我们要了解一个对象XMLHttpRequest(它是 AJAX 的基础哦)

  所有现代浏览器均支持 XMLHttpRequest 对象(IE5 和 IE6 使用 ActiveXObject)。XMLHttpRequest 用于在后台与服务器交换数据,这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。

所以说我们要用ajax就要先创建XMLHttpRequest对象了

View Code
 1  var xmlHttp=false;
 2         /*@cc_on @*/
 3         /*@if(@_jscript_version >= 5)
 4         try{
 5             xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
 6         }catch(e){
 7             try{
 8                 xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
 9             }catch(e){
10                 xmlHttp=false;
11             }
12         }   
13         @end @*/
14         if(!xmlHttp && typeof XMLHttpRequest != 'undefined'){
15             xmlHttp=new XMLHttpRequest();
16         }

为了应对所有的现代浏览器,包括 IE5 和 IE6,我们就写一个比较完善的js来创建这个我们将要用到的对象。

2、创建了操作对象,下面我们来向服务器发送请求吧。

发送请求之前,我们来看看XMLHttpRequest对象成员

XMLHttpRequest成员,对象

属性有

onreadystatechange* 指定当readyState属性改变时的事件处理句柄。只写

readyState 返回当前请求的状态只读.

responseBody 将回应信息正文以unsigned byte数组形式返回.只读

responseStream Ado Stream对象的形式返回响应信息。只读

responseText 将响应信息作为字符串返回.只读

responseXML 将响应信息格式化为Xml Document对象并返回只读

status 返回当前请求的http状态码.只读

statusText 返回当前请求的响应行状态只读

方法

abort 取消当前请求

getAllResponseHeaders 获取响应的所有http

getResponseHeader 从响应信息中获取指定的http

open 创建一个新的http请求并指定此请求的方法、URL以及验证信息(用户名/密码)

 

send 发送请求到http服务器并接收回应

setRequestHeader 单独指定请求的某个http ()

事件

View Code
1 function callServer(){
2             var result=document.getElementById("Search").value;
3             if(result=="" || result==null) return;
4             var url="documentproc/processing1.ashx?key="+escape(result);
5             xmlHttp.open("GET",url,true);
6             xmlHttp.onreadystatechange=updatePage;
7             xmlHttp.send(null);
8             
9         }

 此函数就是向服务器发送请求的过程了,这里我们用到了XMLHttpRequest对象的3个成员

XMLHttpRequest 对象的 open() 和 send() 方法

open() 方法。该方法有五个参数

XMLHttpRequest.open(bstrMethod, bstrUrl, varAsync, bstrUser, bstrPassword);

request-type发送请求的类型。典型的值是GETPOST但也可以发送HEAD 请求。

url要连接的 URL

asynch如果希望使用异步连接则为 true否则为false。该参数是可选的,默认为 true

username:如果需要身份验证,则可以在此指定用户名。该可选参数没有默认值。

password:如果需要身份验证,则可以在此指定口令。该可选参数没有默认值。

 

send(string)方法。string:仅用于 POST 请求

post还是get?

 

 

与 POST 相比,GET 更简单也更快,并且在大部分情况下都能用

 

然而,在以下情况中,请使用 POST 请求。

 

无法使用缓存文件(更新服务器上的文件或数据库)。

向服务器发送大量数据(POST 没有数据量限制)。

发送包含未知字符的用户输入时,POST 比 GET 更稳定也更可靠。 

 

 GET请求

var url="documentproc/processing1.ashx?key="+escape(result);
            xmlHttp.open("GET",url,true);
            xmlHttp.onreadystatechange=updatePage;
            xmlHttp.send(null);

POST请求

xmlhttp.open("POST","documentproc/processing1.ashx",true);
            xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            xmlHttp.onreadystatechange=updatePage;
            xmlhttp.send("key=Bill&lname=Gates");

setRequestHeader(header,value)方法。向请求添加 HTTP 头


3、请求发送成功,我们就等待服务器响应。

View Code
 1 function updatePage(){
 2             if(xmlHttp.readyState==1){
 3                 document.getElementById("stateStr").innerHTML="正在加载文章对象……";
 4             }
 5             if(xmlHttp.readyState==2){
 6                 document.getElementById("stateStr").innerHTML="连接对象加载完毕!";
 7             }
 8             if(xmlHttp.readyState==3){
 9                 document.getElementById("stateStr").innerHTML="数据获取中,请稍后……";
10             }
11             if(xmlHttp.readyState==4){
12                 if (xmlHttp.status==200){
13                     var result=xmlHttp.responseText.split("_");
14                     document.getElementById("stateStr").innerHTML=result[0];
15                 }
16                 else if (xmlHttp.status == 404){
17                     document.getElementById("stateStr").innerHTML="Request URL does not exist,发送的地址错了,没有此页面";
18                 }
19                 else if (xmlHttp.status == 403){
20                     document.getElementById("stateStr").innerHTML="Access denied.无权访问";   
21                 }
22                 else{ 
23                     document.getElementById("stateStr").innerHTML="Error: status code is " + xmlhttp.status;
24                 }
25             }
26         }

request.readyState 的状态

0:请求没有发出(在调用 open() 之前)。

1:请求已经建立但还没有发出(调用 send() 之前)。 一般用不着这之前

2:请求已经发出正在处理之中(这里通常可以从响应得到内容头部)。

3:请求已经处理,响应中通常有部分数据可用,但是服务器还没有完成响应。

4:响应已完成,可以访问服务器响应并使用它

responseText 或 responseXML 属性

document.getElementById("stateStr").innerHTML=xmlHttp.responseText;

responseXML:后面会专门做一个xml的例子。

至此:ajax我算是入门了吧?

 

转载于:https://www.cnblogs.com/charles-master/archive/2012/10/10/2718416.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值