Ajax入门

Ajax简介

Ajax即“Asynchronous JavaScript and XML”(异步的JavaScript与XML技术)

Ajax 是一种用于创建快速动态网页的技术。通过在后台与服务器进行少量数据交换,Ajax 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。

XMLHttpRequest对象是浏览器提供的一个API,用来顺畅地向服务器发送请求并解析服务器响应,当然整个过程中,浏览器页面不会被刷新。

注意,Ajax 只能向同源网址(协议、域名、端口都相同)发出 HTTP 请求,如果发出跨域请求,就会报错。

创建Ajax步骤:

var xhr=new XMLHttpRequest()
xhr.onreadystatechange=function(){
    if(xhr.readyState===4){
        if(xhr.status===200){
            console.log(xhr.responseText)
        }else{
            console.log(new Error(xhr.statusText))
        }
    }   
}
xhr.open('GET','./ajax.html')
xhr.send()

1.创建XMLHttpRequest对象

var xhr = new XMLHttpRequest();

兼容各个浏览器的创建方法:

function createRequest (){
    try {
        xhr = new XMLHttpRequest();
    }catch (tryMS){
        try {
            xhr = new ActiveXObject("Msxm12.XMLHTTP");
        } catch (otherMS) {
            try {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }catch (failed) {
                xhr = null;
            }
        }
    }
    return xhr;
}

2.准备请求

xhr.open(method,url,async);

  • open() 的第一个参数是HTTP请求方法 - 有GET,POST,HEAD以及服务器支持的其他方法。 保证这些方法一定要是大写字母,否则其他一些浏览器(比如FireFox)可能无法处理这个请求。
  • 第二个参数是要作为请求发送目标的URL。
  • 第三个参数是true或false,表示请求是异步还是同步。true是异步,默认true。

3.发送请求

xhr.send();

send() 方法的参数可以是任何你想发送给服务器的内容

4.处理响应

xhr.onreadystatechange=function(){
    if(xhr.readyState===4){
        if(xhr.status===200){
            console.log(xhr.responseText)
        }else{
            console.log(new Error(xhr.statusText))
        }
    }   
}

XMLHttpRequest 的实例属性

  1. onreadystatechange :当处理过程发生变化的时候执行onreadystatechange对应的函数

  2. readyState状态值

  • 0:表示 XMLHttpRequest 实例已经生成,但是实例的open()方法还没有被调用。
  • 1:表示open()方法已经调用,但是实例的send()方法还没有调用,仍然可以使用实例的setRequestHeader()方法,设定 HTTP 请求的头信息。
  • 2:表示实例的send()方法已经调用,并且服务器返回的头信息和状态码已经收到。
  • 3:表示正在接收服务器传来的数据体(body 部分)。这时,如果实例的responseType属性等于text或者空字符串,responseText属性就会包含已经收到的部分信息。
  • 4:表示服务器返回的数据已经完全接收,或者本次接收已经失败。
  1. responseText:服务器以文本字符的形式返回

  2. responseXML:获得 XML形式的响应数据

XMLHttpRequest 的实例属性细节:阮一峰:XMLHttpRequest 对象


myButton=document.getElementById('myButton')
myButton.addEventListener('click',(e)=>{
    let xhr=new XMLHttpRequest()
    xhr.onreadystatechange=()=>{
       if( xhr.readyState===4){
           console.log("请求响应都完毕了")
           if( xhr.status>=200&& xhr.status<300){
               console.log("请求成功")
           }else if( xhr.status>=400){
               console.log("请求失败")
           }
       }
    }
    xhr.open('GET','/xxx')
    xhr.send()
})

当发送请求的时候,就会根据xml.open('GET','/xxx')找到对应的请求路径。在本文是找到/xxx路径,然后返回所请求的数据,在浏览器运行结果如下。

1.png

2.png

原文地址:https://www.cnblogs.com/qfstudy/p/9497639.html