详解JavaScript实现异步Ajax

作者:springsnow 时间:2024-04-16 10:42:25 

一、什么是 AJAX ?

AJAX = 异步 JavaScript 和 XML。AJAX 是一种用于创建快速 * 页的技术。

通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。传统的网页(不使用 AJAX)如果需要更新内容,必需重载整个网页面。

有很多使用 AJAX 的应用程序案例:新浪微博、Google 地图、开心网等等。

1、AJAX是基于现有的Internet标准

AJAX是基于现有的Internet标准,并且联合使用它们:

  • XMLHttpRequest 对象 (异步的与服务器交换数据)

  • JavaScript/DOM (信息显示/交互)

  • CSS (给数据定义样式)

  • XML (作为转换数据的格式)

注意:AJAX应用程序与浏览器和平台无关的!

2、AJAX 工作原理

详解JavaScript实现异步Ajax

二、AJAX - 创建 XMLHttpRequest 对象

1、XMLHttpRequest 对象

XMLHttpRequest 是 AJAX 的基础。所有现代浏览器均支持 XMLHttpRequest 对象(IE5 和 IE6 使用 ActiveXObject)。

XMLHttpRequest 用于在后台与服务器交换数据。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。

2、创建 XMLHttpRequest 对象

所有现代浏览器(IE7+、Firefox、Chrome、Safari 以及 Opera)均内建 XMLHttpRequest 对象。

创建 XMLHttpRequest 对象的语法:

variable=new XMLHttpRequest();

老版本的 Internet Explorer (IE5 和 IE6)使用 ActiveX 对象:

variable=new ActiveXObject("Microsoft.XMLHTTP");

为了应对所有的现代浏览器,包括 IE5 和 IE6,请检查浏览器是否支持 XMLHttpRequest 对象。如果支持,则创建 XMLHttpRequest 对象。如果不支持,则创建 ActiveXObject :

var xmlhttp;
if (window.XMLHttpRequest)
{
   //  IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
   xmlhttp=new XMLHttpRequest();
}
else
{
   // IE6, IE5 浏览器执行代码
   xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

三、向服务器发送请求请求

1、向服务器发送请求

XMLHttpRequest 对象用于和服务器交换数据。

如需将请求发送到服务器,我们使用 XMLHttpRequest 对象的 open() 和 send() 方法:

xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();

方法:

open(method,url,async):规定请求的类型、URL 以及是否异步处理请求。

  • method:请求的类型;GET 或 POST

  • url:文件在服务器上的位置

  • async:true(异步)或 false(同步)

send(string):将请求发送到服务器。string:仅用于 POST 请求

注意:open() 方法的 url 参数是服务器上文件的地址:

xmlhttp.open("GET","ajax_test.html",true);

该文件可以是任何类型的文件,比如 .txt 和 .xml,或者服务器脚本文件,比如 .asp 和 .php (在传回响应之前,能够在服务器上执行任务)。

2、GET 还是 POST?

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

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

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

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

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

3、GET 请求

一个简单的 GET 请求:

xmlhttp.open("GET","/try/ajax/demo_get.php",true);
xmlhttp.send();

在上面的例子中,您可能得到的是缓存的结果。

为了避免这种情况,请向 URL 添加一个唯一的 ID:

xmlhttp.open("GET","/try/ajax/demo_get.php?t=" + Math.random(),true);
xmlhttp.send();

如果您希望通过 GET 方法发送信息,请向 URL 添加信息:

xmlhttp.open("GET","/try/ajax/demo_get2.php?fname=Henry&lname=Ford",true);
xmlhttp.send();

4、POST 请求

一个简单 POST 请求:

xmlhttp.open("POST","/try/ajax/demo_post.php",true);
xmlhttp.send();

如果需要像 HTML 表单那样 POST 数据,请使用 setRequestHeader() 来添加 HTTP 头。然后在 send() 方法中规定您希望发送的数据:

xmlhttp.open("POST","/try/ajax/demo_post2.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Henry&lname=Ford");

5、异步 - True 或 False?

AJAX 指的是异步 JavaScript 和 XML(Asynchronous JavaScript and XML)。

XMLHttpRequest 对象如果要用于 AJAX 的话,其 open() 方法的 async 参数必须设置为 true:

xmlhttp.open("GET","ajax_test.html",true);

对于 web 开发人员来说,发送异步请求是一个巨大的进步。很多在服务器执行的任务都相当费时。AJAX 出现之前,这可能会引起应用程序挂起或停止。

通过 AJAX,JavaScript 无需等待服务器的响应,而是:

  • 在等待服务器响应时执行其他脚本

  • 当响应就绪后对响应进行处理

当使用 async=true 时,请规定在响应处于 onreadystatechange 事件中的就绪状态时执行的函数:

xmlhttp.onreadystatechange=function()
{
   if (xmlhttp.readyState==4 && xmlhttp.status==200)
   {
       document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
   }
}
xmlhttp.open("GET","/try/ajax/ajax_info.txt",true);
xmlhttp.send();

注意:当您使用 async=false 时,请不要编写 onreadystatechange 函数 - 把代码放到 send() 语句后面即可:

xmlhttp.open("GET","/try/ajax/ajax_info.txt",false);
xmlhttp.send();
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

四、AJAX - 服务器 响应

如需获得来自服务器的响应,请使用 XMLHttpRequest 对象的 responseText 或 responseXML 属性。

  • responseText:获得字符串形式的响应数据。

  • responseXML:获得 XML 形式的响应数据。

1、responseText 属性

如果来自服务器的响应并非 XML,请使用 responseText 属性。

responseText 属性返回字符串形式的响应,因此您可以这样使用:

document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

2、responseXML 属性

如果来自服务器的响应是 XML,而且需要作为 XML 对象进行解析,请使用 responseXML 属性:

xmlDoc=xmlhttp.responseXML;
txt="";
x=xmlDoc.getElementsByTagName("ARTIST");
for (i=0;i<x.length;i++)
{
   txt=txt + x[i].childNodes[0].nodeValue + "<br>";
}
document.getElementById("myDiv").innerHTML=txt;

五、AJAX - onreadystatechange 事件

当请求被发送到服务器时,我们需要执行一些基于响应的任务。

每当 readyState 改变时,就会触发 onreadystatechange 事件。

readyState 属性存有 XMLHttpRequest 的状态信息。

1、XMLHttpRequest 对象的三个重要的属性:

1、onreadystatechange:存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。

2、readyState:存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。

  • 0: 请求未初始化

  • 1: 服务器连接已建立

  • 2: 请求已接收

  • 3: 请求处理中

  • 4: 请求已完成,且响应已就绪

3、status:状态。200: "OK";404: 未找到页面

在 onreadystatechange 事件中,我们规定当服务器响应已做好被处理的准备时所执行的任务。

当 readyState 等于 4 且状态为 200 时,表示响应已就绪:

xmlhttp.onreadystatechange=function()
{
   if (xmlhttp.readyState==4 && xmlhttp.status==200)
   {
       document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
   }
}

注意: onreadystatechange 事件被触发 4 次(0 - 4), 分别是: 0-1、1-2、2-3、3-4,对应着 readyState 的每个变化。

2、使用回调函数

回调函数是一种以参数形式传递给另一个函数的函数。

如果您的网站上存在多个 AJAX 任务,那么您应该为创建 XMLHttpRequest 对象编写一个标准的函数,并为每个 AJAX 任务调用该函数。

该函数调用应该包含 URL 以及发生 onreadystatechange 事件时执行的任务(每次调用可能不尽相同):

function myFunction()
{
   loadXMLDoc("/try/ajax/ajax_info.txt",function()
   {
       if (xmlhttp.readyState==4 && xmlhttp.status==200)
       {
           document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
       }
   });
}

六、javascript 脚本化的HTTP----ajax的基石

1、建XMLHttpRequest对象

// This is a list of XMLHttpRequest-creation factory functions to try
HTTP._factories = [
   function() { return new XMLHttpRequest(); },
   function() { return new ActiveXObject("Msxml2.XMLHTTP"); },
   function() { return new ActiveXObject("Microsoft.XMLHTTP"); }
];

// When we find a factory that works, store it here.
HTTP._factory = null;

// Create and return a new XMLHttpRequest object.
//
// The first time we're called, try the list of factory functions until
// we find one that returns a non-null value and does not throw an
// exception. Once we find a working factory, remember it for later use.
//
HTTP.newRequest = function() {
   if (HTTP._factory != null) return HTTP._factory();

for(var i = 0; i < HTTP._factories.length; i++) {
       try {
           var factory = HTTP._factories[i];
           var request = factory();
           if (request != null) {
               HTTP._factory = factory;
               return request;
           }
       }
       catch(e) {
           continue;
       }
   }
   // If we get here, none of the factory candidates succeeded,
   // so throw an exception now and for all future calls.
   HTTP._factory
= function() {
       throw new Error("XMLHttpRequest not supported");
   }
   HTTP._factory(); // Throw an error
}

2、Get请求

HTTP.get = function(url, callback, options) {
   var request = HTTP.newRequest();
   var n = 0;
   var timer;
   if (options.timeout)
       timer = setTimeout(function() {
                              request.abort();
                              if (options.timeoutHandler)
                                  options.timeoutHandler(url);
                          },
                          options.timeout);

request.onreadystatechange = function() {
       if (request.readyState == 4) {
           if (timer) clearTimeout(timer);
           if (request.status == 200) {
               callback(HTTP._getResponse(request));
           }
           else {
               if (options.errorHandler)
                   options.errorHandler(request.status,
                                        request.statusText);
               else callback(null);
           }
       }
       else if (options.progressHandler) {
           options.progressHandler(++n);
       }
   }

var target = url;
   if (options.parameters)
       target += "?" + HTTP.encodeFormData(options.parameters)
   request.open("GET", target);
   request.send(null);
};

1、GET工具

//getText()工具
HTTP.getText = function(url, callback) {
var request = HTTP.newRequest();
request.onreadystatechange = function() {
if(request.readyState == 4 && request.status == 200) {
callback(request.responseText);
}
}

request.open("GET", url);
request.send(null);
}

//getXML()工具
HTTP.getXML = function(url, callback) {
var request = HTTP.newRequest();
request.onreadystatechange = function() {
if(request.readyState == 4 && request.status == 200) {
callback(request.responseXML);
}
}

request.open("GET", url);
request.send(null);
}

3、POST请求

/**
* Send an HTTP POST request to the specified URL, using the names and values
* of the properties of the values object as the body of the request.
* Parse the server's response according to its content type and pass
* the resulting value to the callback function. If an HTTP error occurs,
* call the specified errorHandler function, or pass null to the callback
* if no error handler is specified.
**/
HTTP.post = function(url, values, callback, errorHandler) {
   var request = HTTP.newRequest();
   request.onreadystatechange = function() {
       if (request.readyState == 4) {
           if (request.status == 200) {
               callback(HTTP._getResponse(request));
           }
           else {
               if (errorHandler) errorHandler(request.status,
                                              request.statusText);
               else callback(null);
           }
       }
   }

request.open("POST", url);
   // This header tells the server how to interpret the body of the request.
   request.setRequestHeader("Content-Type",
                            "application/x-www-form-urlencoded");
   // Encode the properties of the values object and send them as
   // the body of the request.
   request.send(HTTP.encodeFormData(values));
};

4、获取Http头(包括解析头部数据)

HTTP.getHeaders = function(url, callback, errorHandler) {
   var request = HTTP.newRequest();
   request.onreadystatechange = function() {
       if (request.readyState == 4) {
           if (request.status == 200) {
               callback(HTTP.parseHeaders(request));
           }
           else {
               if (errorHandler) errorHandler(request.status,
                                              request.statusText);
               else callback(null);
           }
       }
   }
   request.open("HEAD", url);
   request.send(null);
};

// Parse the response headers from an XMLHttpRequest object and return
// the header names and values as property names and values of a new object.
HTTP.parseHeaders = function(request) {
   var headerText = request.getAllResponseHeaders();  // Text from the server
   var headers = {}; // This will be our return value
   var ls = /^"s*/;  // Leading space regular expression
   var ts = /"s*$/;  // Trailing space regular expression

// Break the headers into lines
   var lines = headerText.split(""n");
   // Loop through the lines
   for(var i = 0; i < lines.length; i++) {
       var line = lines[i];
       if (line.length == 0) continue;  // Skip empty lines
       // Split each line at first colon, and trim whitespace away
       var pos = line.indexOf(':');
       var name = line.substring(0, pos).replace(ls, "").replace(ts, "");
       var value = line.substring(pos+1).replace(ls, "").replace(ts, "");
       // Store the header name/value pair in a JavaScript object
       headers[name] = value;
   }
   return headers;
};

5、私有方法

1、获取表单数据:

/**
* Encode the property name/value pairs of an object as if they were from
* an HTML form, using application/x-www-form-urlencoded format
*/
HTTP.encodeFormData = function(data) {
   var pairs = [];
   var regexp = /%20/g; // A regular expression to match an encoded space

for(var name in data) {
       var value = data[name].toString();
       // Create a name/value pair, but encode name and value first
       // The global function encodeURIComponent does almost what we want,
       // but it encodes spaces as %20 instead of as "+". We have to
       // fix that with String.replace()
       var pair = encodeURIComponent(name).replace(regexp,"+") + '=' +
           encodeURIComponent(value).replace(regexp,"+");
       pairs.push(pair);
   }

// Concatenate all the name/value pairs, separating them with &
   return pairs.join('&');
};

2、获取响应:

HTTP._getResponse = function(request) {
switch(request.getResponseHeader("Content-Type")) {
case "text/xml":
return request.responseXML;

case "text/json":
case "text/javascript":
case "application/javascript":
case "application/x-javascript":
return eval(request.responseText);

default:
return request.responseText;
}
}

6、使用:

//提交表单,调用POST方法
var uname = document.getElementById("username");
var usex = document.getElementById("sex");
var formdata = {'username':'tom','sex':'男'};
   HTTP.post("./test.php",formdata, doFun, errorFun);
//请求获取指定的URL的headers
HTTP.getHeaders("./a.html", doFun, errorFun);

来源:https://www.cnblogs.com/springsnow/p/12306710.html

标签:JavaScript,Ajax
0
投稿

猜你喜欢

  • ASP链接Mysql数据库 非DSN连接的方法

    2009-03-09 18:24:00
  • MySQL动态字符串处理DYNAMIC_STRING

    2024-01-26 01:20:19
  • js使用栈来实现10进制转8进制与取除数及余数

    2024-04-19 09:52:12
  • python实现输入三角形边长自动作图求面积案例

    2023-08-12 01:47:49
  • Python实现解析命令行参数的常见方法总结

    2023-10-15 12:31:49
  • Python中格式化字符串的四种实现

    2023-11-25 10:38:18
  • sqlserver数据库导入方法的详细图文教程

    2024-01-15 16:52:24
  • Python基于pillow库实现生成图片水印

    2021-08-01 10:45:38
  • python如何在word中存储本地图片

    2022-09-13 02:17:53
  • python爬虫实战之爬取京东商城实例教程

    2022-05-11 05:33:23
  • 扫盲大讲堂:SQL查询结果集对注入的影响及利用

    2009-09-05 09:49:00
  • 利用XMLBean轻轻松松读写XML

    2008-09-04 11:25:00
  • MySQL数据库十大优化技巧

    2024-01-25 22:51:28
  • python 实现 pymysql 数据库操作方法

    2024-01-22 09:56:29
  • 详细讲解Access数据库远程连接的实用方法

    2008-11-28 16:34:00
  • 关于Python 列表的索引取值问题

    2022-09-08 05:39:54
  • Node.js(安装,启动,测试)

    2024-05-13 09:29:28
  • python 数据类型强制转换的总结

    2021-03-25 03:40:26
  • Python导入模块包原理及相关注意事项

    2023-01-26 04:46:31
  • 如何使用python wasmtime调用rust生成的wasm库

    2023-11-26 23:58:38
  • asp之家 网络编程 m.aspxhome.com