[Data interaction between front and back end] Fetch request encapsulation of native JS

1. Comparison between AJAX and Fetch

1.1 AJAX overview

AJAX is the earliest way to request data, and it does not need to refresh the entire page to update some data.
It belongs to the category of native JS, and the technical core is the XMLHttpRequest object.
AJAX request process: create XMLHttpRequest object, connect to server, send request, receive response data
before general use, we need to encapsulate them for use, as follows:

const ajax = function() {
   
    
    
	// 创建xhr对象
    // 判断浏览器是否支持XMLHttpRequest
    let xhr;
    if (window.XMLHttpRequest) {
   
    
    
        // 高级浏览器
        xhr = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
   
    
    
        // IE低版本
        xhr = new ActiveXObject();
    } else {
   
    
    
        alert('你的浏览器不支持ajax')
    }

	// get 请求	
    this.get = function(url,param) {
   
    
    
        // param 为原始数据类型
        // get请求没有请求体,因此常常将数据放在地址上,作为请求头的一部分(query数据)
        xhr.open('get',url + '?param=' + param,true) // 第三个参数异步与否
        // 监听数据返回
        xhr.onreadystatechange = function() {
   
    
    
            if(xhr.readyState === 4 && xhr.status === 200) {
   
    
    
                

Guess you like

Origin blog.csdn.net/qq_39335404/article/details/131896267
Recommended