谈谈 Ajax

2019-12-28  本文已影响0人  MrAlexLee

Ajax

核心是使用浏览器的内置对象 XMLHttpRequest 对象。
IE5 和 IE6 使用的是 ActiveXObiect 对象。
写法:
1,创建对象

let xmlHttp = new XMLHttpRequest();  

2,发起请求
2-1,发起 get 请求

xmlHttp.open ('get' , 'url' , true);  
xmlHttp.send()  

2-2,发起 get 请求传参

xmlHttp.open ('get' , 'url+参数 ' , true);  
xmlHttp.send()  

2-3,发起 post 请求

xmlHttp.open ('post' , 'url' , true);  
xmlHttp.send()  

2-4,post 数据请求
注意:要使用 setRequestHeader()来添加 HTTP 请求头。然后在send()方法中传参

xmlHttp.open ('post' , 'url' , true);  
xmlHttp.setRequestHeader('Content-type' , ' application/x-www-form-urlencoded ')  
xmlHttp.send(' fname=bill&Iname=gates ')  

3,xmlHttpRequest的 onreadystatechange 函数
描述:当请求的 readystate 发生改变的时候就会自动调用该函数,所以只要写明函数内会执行什么逻辑即可。此状态有以下五种:
0:请求未初始化
1:服务器连接已经建立
2:请求已经接受
3:请求在处理中
4:请求已经完成且响应就绪

此外请求还有一个状态 status,有 200 和404 两种

举个栗子:

xmlhttp.onreadystatechange=function()  
  {  
  if (xmlhttp.readyState==4 && xmlhttp.status==200)  
    {  
        //执行逻辑  
    }  
  }  

4,服务器的响应
经过上面三个步骤以后我们可以得到响应,那么 xmlHttp 的 响应分为两种:responseText 和 responseXML 属性
responseText是以字符串的形式响应数据
responseXML是以 XML 形式响应数据

上一篇 下一篇

猜你喜欢

热点阅读