JS implements Ajax request background interface

The project premise of writing this article is that the company cooperates with a third party, we provide the H5 page to the third party, and the third party embeds our page on their main page. The red box in the middle is the picture we want to provide.

1. Native JS implementation

Native JS is relatively simple and clear to understand. Here I extract both the get request and the post request.

// obj包括接口参数、接口地址、请求类型
// successFun成功回调
// errorFn失败回调
// flag 同步、异步   true-异步
function httpAjax(obj, successFun, errorFn){
    var xmlHttp = null;
    if(window.XMLHttpRequest){
        xmlHttp = new XMLHttpRequest;
    }else if(window.ActiveXObject){
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    var httpMethod = obj.method.toUpperCase();
    var httpUrl = obj.url;
    var requestData = JSON.stringify(obj.data) || {};
    xmlHttp.onreadystatechange = () => {  //每当 readyState 属性改变时,就会调用该函数
		if(xhr.readyState === 4 && (xhr.status >= 200 && xhr.status < 300)) {
			//请求成功执行的回调函数
			successFun(xmlHttp.responseText);
		}else {
            errorFn()
        }
	}
    
    //请求接口
	if(httpMethod == 'GET'){
		xmlHttp.open("GET",httpUrl,obj.flag);
		xmlHttp.send();
	}else if(httpMethod == "POST"){
		xmlHttp.open("POST",httpUrl,obj.flag);
		xmlHttp.setRequestHeader("Content-Type","application/json");
		xmlHttp.send(requestData);
	}
   
}



// 调用方式
let params = {
    flag: true, //异步请求
    data: {}, //接口数据
    url: 接口地址,
    method: "post"
}
httpAjax(params, function(res){
    let result = JSON.parse(res) // JSON.parse() 方法用来解析JSON字符串,构造由字符串描述的JavaScript值或对象
}, function(){
    console.log("返回错误")
})

2. Use Promise to achieve

Using Promise to realize the callback method does not seem to be more advanced~haha;

It is recommended to understand the basic principles of Promise first.

function httpAjax(obj){
    const p = new Promise((resolve, reject) => {
        var xmlHttp = new XMLHttpRequest()
        var httpMethod = obj.method.toUpperCase();
        var httpUrl = obj.url;
        var requestData = JSON.stringify(obj.data) || {};
        xmlHttp.onreadystatechange = () => {  //每当 readyState 属性改变时,就会调用该函数
		    if(xhr.readyState === 4 && (xhr.status >= 200 && xhr.status < 300)) {
			   resolve(JSON.parse(xhr.responseText))
		    }else {
                reject("错误")
            }
	    }
    
        //请求接口
	    if(httpMethod == 'GET'){
		    xmlHttp.open("GET",httpUrl,obj.flag);
		    xmlHttp.send();
	    }else if(httpMethod == "POST"){
		    xmlHttp.open("POST",httpUrl,obj.flag);
		    xmlHttp.setRequestHeader("Content-Type","application/json");
		    xmlHttp.send(requestData);
	    }
    
    })

    return p
   
}


// 调用

httpAjax(url).then(res => {console.log(res)}).catch(reason => {console.log(reason)})

Guess you like

Origin blog.csdn.net/codingLeader/article/details/125439250