原生ajax请求

1,343 阅读2分钟

原生ajax

原生发送ajax大致可分为5步:

  1. 实例化XMLHttpRequest对象。
  • XMLHttpRequest() 是内置的 JavaScript 对象。它是浏览器提供的原生 API,无需任何额外的库或框架。你可以直接在 JavaScript 代码中使用 XMLHttpRequest() 对象,而无需进行任何安装或导入。
  1. 设置请求方法和地址。
  • 使用open()方法设置
  1. 设置请求头
  • 可以省略 如果后端需要,就要设置,不需要,设置了也没关系,可以自定义
  • setRequestHeader()
  1. 注册回调函数
  2. 发送请求
  • send()

示例:

  function ajax_get() {
            // 1. 实例化xhr对象
            const xhr = new XMLHttpRequest()
            // 2. 设置请求方法和地址 
            xhr.open('get', 'http://ajax-api.itheima.net/api/news')
            // 3. 设置请求头 (可省略,看需)
            xhr.setRequestHeader('myHeader', 'goodHeader')
            // 4. 注册回调函数  
            //  readystatechange  ==> 表示ajax请求的状态改变
            // xhr.readystate ==> 从我们实例化xhr对象开始,就在变化 0-4 值, 4 表示服务器已经把数据返回给我了
            xhr.addEventListener('readystatechange', function () {
                if (xhr.readyState === 4) {

                    
                    if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
                        console.log(xhr.response)
                    } else {
                        console.log('请求不成功')
                    }

                }
            })

            // 5. 发送请求
            xhr.send()
        }

xhr.readyState

  • 表示ajax xhr当前的状态码。
  • 返回值是 0、1、2、3、4
  • image.png

xhr.status

  • xhr.status 它实际上就是http状态码

  • 304: 资源未修改

  • 协商缓存: 两个请求头:一个是 If-Modified-since / If-None-match

  • 览器在发送请求的时候,附加一个请求头,去问服务器,资源有没有改动。

  • 服务器,看到了这个请求头, 就会去它自己的本地查看一下是否修改,如果没有修改,返回304

  • 告诉浏览器,资源没有修改,你可以直接用上次请求的那个资源。

xhr的load

  • load 表示的是 readyStateChange4 即为load事件, 一次ajax请求,只会触发一次。

示例:

      function ajax_get() {
            const xhr = new XMLHttpRequest()
            xhr.open('get', 'http://ajax-api.itheima.net/api/news')
            xhr.setRequestHeader('myHeader', 'goodHeader')
            // 一次ajax请求
            xhr.addEventListener('load', function () {
                    if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
                        console.log(xhr.response)
                        console.log(xhr.responseText)
                    } else {
                        console.log('请求不成功')
                    }
            })
            xhr.send()
        }
  • 就只是改变了监听事件
  • xhr.response 是根据响应头里面的 content-type自动解析的,一般是二进制的数据,音视频
  • xhr.responseText 一般是文本数据,比如htmljson,纯文本。

原生Ajax-get-请求传参

  • 原生的ajaxget没有params,所以,直接拼接到url上。
  • 查询字符串 queryString url?key=val&key2=val2

示例:

      function ajax_get() {
            const xhr = new XMLHttpRequest()
             // ===> 查询字符串  queryString   url?key=val&key2=val2
            xhr.open('get','http://ajax-api.itheima.net/api/robot?spoken=吃了没')
            xhr.addEventListener('load',function(){
                if(xhr.status >= 200 && xhr.status < 300 || xhr.status
                 === 304) {
                    console.log(xhr.response)
                 }
            })
            xhr.send()
        }
  • 直接拼接在open()方法url后面

原生Ajax-post-请求传参

  • 如果是post请求,原生ajax,需要设置一个请求头,告诉后端,我发送的数据是什么格式的。
  • 后端接口文档中写了需要什么样格式的数据!,我们照着设置就好了

示例:

 function ajax_get() {
            const xhr = new XMLHttpRequest()
            xhr.open('post','http://ajax-api.itheima.net/api/login')
            // 如果是post请求,原生ajax,需要设置一个请求头,告诉后端,我发送的数据是什么格式的
            xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
            xhr.addEventListener('load',function(){
                if(xhr.status >= 200 && xhr.status < 300 || xhr.status
                 === 304) {
                    console.log(xhr.response)
                 }
            })
            // post请求,在这里写参数
            // 如果是get请求,send可以为空,或者null
            xhr.send('username=admin&password=123456')
        }
  • 请求参数写在send()方法中