鍍金池/ 問答/HTML/ for循環(huán)接口請求,怎么在成功后知道當(dāng)前請求成功的是哪個

for循環(huán)接口請求,怎么在成功后知道當(dāng)前請求成功的是哪個

在循環(huán)請求后,不支持es6語法,也不傳給服務(wù)器json格式,接口只會返回成功狀態(tài),沒有任何的標(biāo)識,在前端怎么知道當(dāng)前傳遞成功的是哪個數(shù)組元素。謝謝

var arr = [{
  gymAddr: "00000000",
  trainingActionId: "123",
  deviceId: "1"
}, {
  gymAddr: "00000000",
  trainingActionId: "123",
  deviceId: "2"
}, {
  gymAddr: "00000000",
  trainingActionId: "123",
  deviceId: "3"
}]

for (var i = 0; i < arr.length; i++) {
  wx.request({
    url: "https://localhost:8080/trainingRecord/single",
    data: arr[i],
    method: 'POST',
    header: {
      'content-type': 'application/x-www-form-urlencoded'
    },
    success: function(res) {
      console.log('res', res);
      console.log(this)
    }
  })
}
回答
編輯回答
乖乖瀦

閉包 或者用forEach 里邊的索引作為索引

2018年3月6日 02:19
編輯回答
筱饞貓
for (let i = 0; i < arr.length; i++) { // 注意這一行
  request({
    url: "https://localhost:8080/trainingRecord/single",
    data: arr[i],
    method: 'POST',
    header: {
      'content-type': 'application/x-www-form-urlencoded'
    },
    success: function(res) {
      console.log('res', res, i);
      console.log(this)
    }
  })
}

或者:

for (var i = 0; i < arr.length; i++) {
 // 注意下面這一行
  (function(i){
    request({
        url: "https://localhost:8080/trainingRecord/single",
        data: arr[i],
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function(res) {
          console.log('res', res, i);
          console.log(this)
        }
    })
  })(i)
}
2017年10月1日 04:30
編輯回答
故林
for (var i = 0; i < arr.length; i++) {
    (function(){
        var _i=i;
        wx.request({
        ...
        })
    })()
}
2017年3月26日 15:18
編輯回答
墨小白
var arr = [{
  gymAddr: "00000000",
  trainingActionId: "123",
  deviceId: "1"
}, {
  gymAddr: "00000000",
  trainingActionId: "123",
  deviceId: "2"
}, {
  gymAddr: "00000000",
  trainingActionId: "123",
  deviceId: "3"
}]

for (let i = 0; i < arr.length; i++) {
  wx.request({
    url: "https://localhost:8080/trainingRecord/single",
    data: arr[i],
    method: 'POST',
    header: {
      'content-type': 'application/x-www-form-urlencoded'
    },
    success: function(res) {
      console.log('res', res);
      console.log(this)
      if(res.status == 200){
          console.log(i)
      }
    }
  })
}
2017年9月16日 11:46