ajax从基础开始

  ajax的实现主要依靠浏览器内部的XMLHttpRequest对象,XMLHttpRequest对象在所有现代的浏览器中都被实现了,虽然它还没有被标准化,目前仅是W3C的一个Working Draft. 套用下W3C对它的描述:

The XMLHttpRequest specification defines an API that provides scripted client functionality for transferring data between a client and a server.

不过IE对于该对象的实现与其他浏览器有所不同,它把它实现为ActiveX对象。下面的createXMLHttp()方法和startRequest() 方法展示了如何在客户端脚本中发起Http请求。XMLHttpRequest对象有几个常用属性,分别是:

属性 描述
onreadystatechange 每个状态变化都会触发这个事件处理器
readyState 请求的状态 0 未初始化 1 正在加载 2 已经加载 3 交互中 4 完成
responseText 服务器返回的值
status HTTP响应代码 200 OK 404 Not Found 等
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Ajax From Beginning</title>
<script type="text/javascript">
 var jsdebug={ 
        print:function(content,elementID){
            var id;
            if(arguments.length==1){
                id='debug';
            } else
               id=elementID;
            var element=document.getElementById(id);
            if(element)
               element.innerHTML+=content;     
        }
    };

var xmlHttp;
function createXMLHttp(){
    if(window.ActiveXObject){
        xmlHttp=new ActivXObject("Microsoft.XMLHTTP");
    }else if(window.XMLHttpRequest){
        xmlHttp=new XMLHttpRequest();
    }
}

function startRequest() {
    createXMLHttp();
    xmlHttp.onreadystatechange = handleStateChange;
    xmlHttp.open("GET", "HandleParam.ashx?country=china", true);
    xmlHttp.send(null);
}

function handleStateChange() {
    if (xmlHttp.readyState == 4) {
        if (xmlHttp.status == 200) {
            jsdebug.print(xmlHttp.responseText);
        }
    }   
}                    
</script>
</head>
<body>
<form action='#'>
   <input type="button" value="click me" onclick="startRequest()" />
</form>
<div id="debug"></div>
</body>
</html>
 
客户端发起请求的方式和访问普通网页的时候是类似的,只需要设置好正确的url就可以。将这个文件保存成ajax.htm并且设为起始页面。下面介绍服务器端代码,在VS中新建一个网站,添加一个Genric Handler,命名为HandleParam.ashx。
image 
其响应代码为:
public class HandleParam : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        string s = context.Request.QueryString["country"];
        string response = "Unknown";
        if (s.ToLower() == "china")         
            response = "Beijing";         
        else if (s.ToLower() == "usa")
            response = "Washington";
        context.Response.Write(string.Format("Respnose From Server, the capital of {0} is {1}!",
            s,response));        
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }
}
 
运行项目:
image 
最后一行文字就是从服务器端获得的值。
原文地址:https://www.cnblogs.com/yinzixin/p/1632112.html