第三章 web前端开发工程师--JavaScript进阶程序设计 3-17 同步调用与异步调用 AJAX

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wgf5845201314/article/details/90811982

JavaScript 异步调用AJAX

 

本节课所讲内容:

1.XMLHttpRequest

2.GET与POST

主讲教师:Head老师

一. XMLHttpRequest

Ajax技术核心是XMLHttpRequest对象(简称XHR),这是由微软首先引入的一个特性,其他浏览器提供商后来都提供了相同的实现。在XHR出现之前,Ajax式的通信必须借助一些hack手段来实现,大多数是使用隐藏的框架或内嵌框架。

IE7+、Firefox、Opera、Chrome和Safari都支持原生的XHR对象,在这些浏览器中创建XHR对象可以直接实例化XMLHttpRequest即可。

var xhr = new XMLHttpRequest();

alert(xhr);                                                       //XMLHttpRequest

 

在使用XHR对象时,先必须调用open()方法,它接受三个参数:要发送的请求类型(get、post)、请求的URL和表示是否异步。

xhr.open('get', 'demo.php', false);                         //对于demo.php的get请求,false同步

demo.php的代码如下:

<?php echo Date('Y-m-d H:i:s')?>                          //一个时间

open()方法并不会真正发送请求,而只是启动一个请求以备发送。通过send()方法进行发送请求,send()方法接受一个参数,作为请求主体发送的数据。如果不需要则,必须填null。执行send()方法之后,请求就会发送到服务器上。

xhr.send(null);                                                       //发送请求

当请求发送到服务器端,收到响应后,响应的数据会自动填充XHR对象的属性。那么一共有四个属性:

 

属性名

说明

responseText

作为响应主体被返回的文本

responseXML

如果响应主体内容类型是"text/xml"或"application/xml",则返回包含响应数据的XML DOM文档

status

响应的HTTP状态

statusText

HTTP状态的说明

 

接受响应之后,第一步检查status属性,以确定响应已经成功返回。一般而已HTTP状态代码为200作为成功的标志。除了成功的状态代码,还有一些别的:

HTTP状态码

状态字符串

说明

200

OK

服务器成功返回了页面

400

Bad Request

语法错误导致服务器不识别

401

Unauthorized

请求需要用户认证

404

Not found

指定的URL在服务器上找不到

500

Internal Server Error

服务器遇到意外错误,无法完成请求

503

ServiceUnavailable

由于服务器过载或维护导致无法完成请求

 

接下来我们使用ajax获取服务器端的时间日期

<input type="button" id="ad" value="点击">

var ad = document.getElementById("ad");

       ad.onclick=function(){

              var xhr = new XMLHttpRequest();

              xhr.open('get', 'demo.php', false);   

              xhr.send(null);

              if (xhr.status == 200) {

                     alert(xhr.responseText);                                 

              } else {

                     alert('获取数据错误!错误代号:' + xhr.status + ',错误信息:' + xhr.statusText);

              }

       }

同步调用固然简单,但使用异步调用才是我们真正常用的手段。使用异步调用的时候,需要触发readystatechange事件,然后检测readyState属性即可。这个属性有五个值:

状态

说明

0

未初始化

尚未调用open()方法

1

启动

已经调用open()方法,但尚未调用send()方法

2

发送

已经调用send()方法,但尚未接受响应

3

接受

已经接受到部分响应数据

4

完成

已经接受到全部响应数据,而且可以使用

var ad = document.getElementById('ad');

           ad.onclick=function(){

                  var xhr = new XMLHttpRequest();

                  xhr.onreadystatechange=function(){

                         if(xhr.readyState==4){

                                if(xhr.status==200){    

                                       alert(xhr.responseText);

                                }else{     

                                       alert('数据返回失败!状态代码:' + xhr.status + '状态信息:' + xhr.statusText);

                                }

                         }

                  }

                  xhr.open('get','demo.php',true);       //false同步

                  xhr.send(null);

           }

二.GET与POST

在提供服务器请求的过程中,有两种方式,分别是:GET和POST。在Ajax使用的过程中,GET的使用频率要比POST高。

//使用getResponseHeader()获取单个响应头信息

alert(xhr.getResponseHeader('Content-Type'));

 

//使用getAllResponseHeaders()获取整个响应头信息

alert(xhr.getAllResponseHeaders());

GET请求

GET请求是最常见的请求类型,最常用于向服务器查询某些信息。必要时,可以将查询字符串参数追加到URL的末尾,以便提交给服务器。

              var ad = document.getElementById('ad');

              ad.onclick=function(){

                     var xhr = new XMLHttpRequest();

                     xhr.onreadystatechange=function(){

                            if(xhr.readyState==4){

                                   if(xhr.status==200){

                                          //alert(xhr.getResponseHeader('Content-Type'));  

                                          //alert(xhr.getAllResponseHeaders());

                                          alert(xhr.responseText);

                                   }else{     

                                          alert('数据返回失败!状态代码:' + xhr.status + '状态信息:' + xhr.statusText);

                                   }

                            }

                     }

                     xhr.open('get','demo.php?rand='+ Math.random(),true);     //false同步   

                     xhr.send(null);

              }

POST请求

POST请求可以包含非常多的数据,我们在使用表单提交的时候,很多就是使用的POST传输方式。

xhr.open('post', 'demo.php', true);

 

而发送POST请求的数据,不会跟在URL的尾巴上,而是通过send()方法向服务器提交数据。

xhr.send('name=Lee&age=100');

 

一般来说,向服务器发送POST请求由于解析机制的原因,需要进行特别的处理。因为POST请求和Web表单提交是不同的,需要使用XHR来模仿表单提交。

xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

var ad = document.getElementById('ad');

              ad.onclick=function(){

                     var xhr = new XMLHttpRequest();

                     xhr.onreadystatechange=function(){

                            if(xhr.readyState==4){

                                   if(xhr.status==200){

                                          alert(xhr.responseText);

                                   }else{     

                                          alert('数据返回失败!状态代码:' + xhr.status + '状态信息:' + xhr.statusText);

                                   }

                            }

                     }

                     xhr.open('post','demo.php',true);      //true异步    

                     xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

                     xhr.send('name=Head');

                    

              }

 

 

 

猜你喜欢

转载自blog.csdn.net/wgf5845201314/article/details/90811982