/** * @function ajax request * @fields ajaxName:请求名称,method:请求方法,url:接口地址,async:是否异步请求,withCredentials:是否支持跨域发送cookie,params:post请求参数 * @param data:{"ajaxName":"ajaxNameString","method":"GET/POST","url":"","async":true/false,"withCredentials":true/false,"params":{}} * @result ajaxName.responseText */ function ajaxRequest(data, callback) { var ajax = data.ajaxName; // 新建请求 ajax = new XMLHttpRequest(); // 打开请求 ajax.open(data.method, data.url, data.async); // 是否支持跨域发送cookie ajax.withCredentials = data.withCredentials; // 如果是POST请求则设置Header if (data.method == ‘POST‘) { ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); } // 发送请求 ajax.send(data.params ? data.params : ‘‘); // 注册事件 ajax.onreadystatechange = function () { callback(ajax); } } 调用方法: ajaxRequest({ "ajaxName": ajaxName, "method": "POST", "url": "http://xxx.xxx.xxx/", "async": true, "withCredentials": true, "params": params }, function callback(ajax) { console.log(ajax.responseText); })
原文地址:https://www.cnblogs.com/Man-Dream-Necessary/p/8659463.html
时间: 2024-10-20 15:35:51