ajax的原理是什么,如何去实现?

360 阅读3分钟

一、介绍

说起ajax,它的全称是Async JavaScript and Xml,也就是异步传输js和Xml,是一种创建交互式网页开发技术,可以在不从新加载网页的情况下,与服务器交换数据,并且更新部分网页。

二、ajax原理以及流程

Ajax的原理简单来说就是通过XmlHttpRequest对象来向服务器发送异步请求,从服务器获取数据,js来操作dom而更新界面。

流程如下: 浏览器创建一个XmlHttpRequest对象,发送异步请求HttpRequest,通过互联网,服务器接收这个HttpRequest请求,返回请求,最后通过互联网浏览器接收返回数据,用js操作dom来更新页面。

举个例子: 老师想找班长汇报一下班级工作,就委托学委去叫班长,老师自己就接着做其他事情,直到学委告诉老师班长已经到了,最后班长跟给老师汇报工作。 Ajax请求数据流程与上述基本一致,上述的学委相当于XMLHttpRequest对象,老师相当于浏览器,响应数据相当于班长。 浏览器可以发送http请求后,接着做其他的事情,等收到xhr返回来的数据再次进行操作。

三、实现过程

实现ajax异步交互需要服务器逻辑进行配合,需要完成以下的步骤:

(1)创建xhr实例对象,也就是const xhr = new XMLHttpRequest

const xhr = new XMLHttpRequest()

(2)通过xhr来open()方法与服务器建立连接;

xhr.open(method,url,[async],[user],[password])

参数说明

method:表示当前的请求方式,常见的有get,post

url:服务端地址

async:是否异步,默认是true

user:可选的用户用于认证用途,默认为null

password:可选的密码用于认证用途,默认为null

(3)构建请求数据的内容,通过xhr.send()方法来进行发送,发送到服务端。

xhr.send([body])

body: 在 XHR 请求中要发送的数据体,如果不传递数据则为 null

如果使用GET请求发送数据的时候,需要注意如下:

  • 将请求数据添加到open()方法中的url地址中
  • 发送请求数据中的send()方法中参数设置为null (4)通过xhr对象提供的onreadystatechange事件监听服务端你的通信状态。 onreadystatechange 事件用于监听服务器端的通信状态,主要监听的属性为XMLHttpRequest.readyState 关于XMLHttpRequest.readyState属性有五个状态,如下图显示

image.png 只要readyState属性值发生变化,就会触发一次readystatechange事件 。 XMLHttpRequest.responseText属性用于接收服务器端的响应结果

(5)接受并且处理服务端向客户端响应的数据

const xhr = new XMLHttpRequest()
        xhr.open('post', 'http://127.0.0.1:3000')
        xhr.send()
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4) {
                if (xhr.status >= 200 && xhr.status <= 300) {
                    success('成功的回调')
                    console.log(xhr.responseText);
                } else if (xhr.status >= 400) {
                    failure('失败的回调')
                    console.log('错误信息' + xhr.status);
                }
            }
        }

四、封装

上面我们了解了ajax发送请求的过程,这样我们就可以模拟实现一下其相应的封装,从下面几个方面, 1.请求类型, 2.请求数据 3.请求地址 4.数据类型(json) 5.成功/失败的回调

 function ajax(options) {
    const xhr = new XMLHttpRequest()
    options = options || {}
    options.type = (options.type || 'GET').toUpperCase()
    options.datatype = options.datatype || 'json'
    const params = options.data
    if (options.type === 'GET') {
        xhr.open('GET', options.url + '?' + params, true)
        xhr.send(null)
    } else if (options.type === 'POST') {
        xhr.open('POST', options.url, true)
        xhr.send(params)
    }
    // 接受请求
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            let status = xhr.status
            if (status >= 200 && status < 300) {
                options.success && options.success(xhr.responseText, xhr.responseXML)
            } else {
                options.fail && options.fail(status)
            }

        }
    }
}
//使用
ajax({
    type: 'get',
    datatype: 'json',
    data: {},
    url: 'http://127.0.0.1:3000',
    success: function(text, xml) {
        console.log(text, xml);
    },
    fail: function(status) {
        console.log(status);
    }
})