js for循环调用ajax 函数封装 闭包 回调

xiaoxiao2021-02-28  92

      此次在编写代码时遇到for循环中发送ajax请求,遇到的问题是for循环完后,才执行ajax请求一次,通过网上查找资料,解决方法记录如下:

      1.方法一:

for(var i = 0; i < 3; i++){ setTimeout((function (i) {     return function () {                 $.ajax({                 type: "POST",                 url: url,                 dataType: "json",                 contentType: "application/json;utf-8",                 data: data,                 timeout: 6000,                 error: function () {                                     },                 success: function (response) {                                      }             });         }     })(i), 10); }   2.方法二:    function getUserInfo(data) { return $.ajax({ type: "POST", url: "/user", dataType: "json", contentType: "application/json;utf-8", data: data, timeout: 6000 }); } getUserInfo(data) .done(function (response) { console.log(response); }) .fail(function () { //TODO });

转载请注明原文地址: https://www.6miu.com/read-31050.html

最新回复(0)