使用原生JS编写ajax操作XMLHttpRequst对象
ajax其本质就是XMLHttpRequest,现在jquery调用异步的方法很方便,但是也不能忘记原生的JS去编写ajax;
需要注意的是,很多人在写的时候喜欢只用XMLHttpRequest对象readyState 值去判断请求状态和结果,而readyState 的值也有不同的说明
当readyState 的值为0的时候,请求还未初始化(还没有调用open()方法)
当readyState 的值为1的时候,请求刚建立,但是还没有发送(还没有调用 Send()方法)。
当readyState 的值为2的时候请求已发送,但是是获取不到XMLHttpRequest对象的响应信息的
当readyState 的值为3和4的时候,XMLHttpRequest已经能获取到响应信息了,当值为3时,请求其实还在处理;但是已经可以获取到信息,只是服务器还没有完成响应的生成。
以下是一个简单的ajax
前端代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AjaxTest.aspx.cs" Inherits="WebApplication21.AjaxTest" %> <!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 ajaxRequest(type, prames) { var xmlrequest = null; if (window.ActiveXObject) { xmlrequest = new ActiveXObject("Microsoft.XMLHTTP"); } else { xmlrequest = new XMLHttpRequest(); } if (xmlrequest != null) { //alert("1"); if (type == 1) { xmlrequest.open("Get", "ajaxhandler.ashx", true); } else { xmlrequest.open("POST", "ajaxhandler.ashx", true); } xmlrequest.onreadystatechange = function () { if (xmlrequest.status == 200 && xmlrequest.readyState == 4) { alert(xmlrequest.responseText.toString()); } // else if (xmlrequest.readyState == 2) { // alert("请求失败," + xmlrequest.status + ":" + xmlrequest.responseText); // } }; xmlrequest.send(null); } } //以post方式提交 function PostAjax() { ajaxRequest(0); } //以GET方式提交 function GetAjax() { ajaxRequest(1); } </script> </head> <body> <form id="form1" runat="server"> <div> <a onclick="ajaxRequest(0)">模拟POST提交</a><br /> <a onclick="ajaxRequest(1)">模拟GET提交</a> </div> </form> </body> </html>
这里的C#代码是写在一般处理程序里面的(后缀为ashx的文件):
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.Write(context.Request.RequestType.ToString() + ":Hello World"); //int type = int.Parse(context.Request["type"].ToString()); //if (type==1) //{ // context.Response.Write("GET:Hello World"); //} //else //{ // context.Response.Write("POST:Hello World"); //} } public bool IsReusable { get { return false; } }
XMLHttpRequest对象有很多封装好的方法,可以进行请求设置,这里不多说,之所以写这篇博客,之前有人问我有没有用原生的JS写过ajax,之前确实没写过,也就直接说了没有,其实我所知道的和我知道却没写过
也没用过的技术多了去了,不过没写过,不代表我不会写。