浏览器自定义Ajax函数批量调接口

function Ajax(type, url, data, success, failed, async){
    // 创建ajax对象
    var xhr = null;
    if(window.XMLHttpRequest){
        xhr = new XMLHttpRequest();
    } else {
        xhr = new ActiveXObject('Microsoft.XMLHTTP')
    }
  
    var type = type.toUpperCase();
    // 用于清除缓存
    var random = Math.random();
  
    if(type == 'GET'){
        if(data){
            xhr.open('GET', url + '?' + data, async);
        } else {
            xhr.open('GET', url + '?t=' + random, async);
        }
        xhr.send();
    } else if(type == 'POST'){
        xhr.open('POST', url, true);
        // 如果需要像 html 表单那样 POST 数据,请使用 setRequestHeader() 来添加 http 头。
        xhr.setRequestHeader("Content-type", "application/json");
        xhr.send(JSON.stringify(data));
    //xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        //xhr.send(data);
    }
     
    // 处理返回数据
    xhr.onreadystatechange = function(){
        if(xhr.readyState == 4){
            if(xhr.status == 200){
        console.log("xhr success");
                success(xhr.responseText);
            } else {
                if(failed){
              console.log("xhr failed");
                      failed(xhr.status);
                }
            }
        }
    }
}



var e = function(error){
    console.log(error);
}

var f = function(data){
   console.log(data);
}


document.getElementsByClassName("ant-pagination-item-link")[1].click();
for (var i = 0; i < document.getElementsByClassName("ant-list-item-meta-title").length; i++) {
    var taskId = document.getElementsByClassName("ant-list-item-meta-title")[i].childNodes[0].innerText;
    console.log(taskId);
    Ajax('post', "https://cc.xxx.com/xxx/v1/finish", {
        "taskId": taskId,
        "operator": "xxx",
        "comment": "1"
    }, f, e, true);
}

var taskIds = [];
for (var j = 0; j < taskIds.length; j++) {
	var taskId = taskIds[j];
	console.log(taskId);
	Ajax('post', "https://xxx.xxx.com/api/customer/completeTask", {
        "taskId": taskId,
        "remark": "完成任务",
        "operator": "xxx"
    }, f, e, true);
}
posted @ 2020-05-29 12:42  商商-77  阅读(205)  评论(1编辑  收藏  举报