jQuery从AJAX调用中返回返回数组的AJAX调用并获取生成的数组

时间:2017-12-14 19:42:42

标签: javascript jquery ajax

我在页面加载时触发调用并返回一个数组。现在,对于数组中存在的每个名为groupId的元素,我必须触发另一个调用以获取组名和组注释。

现在我需要创建一个最终数组,该数组将从第一个调用返回该数组,并与第二个调用返回的相应组名和信息合并。

这是从第一个调用返回的数组:

[{
  "customMessage": "THis is the first message",
  "groupIdx": 13
}, {
  "customMessage": "This is the second message",
  "groupIdx": 14
}]

我正在做的事情:

$.ajax({
  type: "GET",
  url: '<html:rewrite page="/rest/pre-visit-instruction/list"/>',
  dataType: "json"
}).done(function(data) {
  vueInst.preVisitInstructions = data;
});

现在我要添加一个.each函数并调用另一个来电。

这是最终代码:

$.ajax({
    type: "GET",
    url: '<html:rewrite page="/rest/pre-visit-instruction/list"/>',
    dataType: "json"
  }).done(function(data) {
    vueInst.preVisitInstructions = data;
  }).each(dataObj, function(j, data) {
      $.ajax({
        type: "GET",
        url: '<html:rewrite page="/rest/group/"/>' + data.groupIdx + '/info',
        dataType: "json"
      }).

我的问题是:如何从.each函数返回数据并将其附加到原始对象?

1 个答案:

答案 0 :(得分:-1)

$.each()函数必须位于.done()函数内。

更新:根据上一条评论:

您应该使用Array#filter

data.data = response2.filter(function(x) {
  return x.groupId === data.groupIdx;
});

这样的事情:

$(function() {
  var vueInst = {
    preVisitInstructions: []
  };
  var result = [];

  $.ajax({
    type: "GET",
    url: "https://gist.githubusercontent.com/dannyjhonston/17455e3ef90fb3cf096d1f051d4331e5/raw/ad51c85e7722a83e7085ad63e26a524b769efe50/firstData.json",
    dataType: "json"
  }).done(function(response1) {
    $.each(response1, function(j, data) {
      $.ajax({
        type: "GET",
        url: "https://gist.githubusercontent.com/dannyjhonston/e610dd23f830b108bc1e24c78f66b3b6/raw/54851535eedd1e94a1a944ddf3d63412e83349f8/secondData.json",
        dataType: "json"
      }).done(function(response2) {
        data.data = response2.filter(function(x) {
          return x.groupId === data.groupIdx;
        });
        result.push(data);
      });
      vueInst.preVisitInstructions = result;
    });
  });
  $("#btnCheck").on("click", function() {
    console.log(JSON.stringify(vueInst.preVisitInstructions));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="btnCheck">Check data</button>

结果应为:

[{
    "customMessage": "THis is the first message",
    "groupIdx": 13,
    "data": [

    ]
  },
  {
    "customMessage": "This is the second message",
    "groupIdx": 14,
    "data": [{
        "groupId": 14,
        "groupName": "Test 1",
        "groupNotes": "THis is a note"
      },
      {
        "groupId": 14,
        "groupName": "Test 2",
        "groupNotes": "THis is a note"
      },
      {
        "groupId": 14,
        "groupName": "Test 3",
        "groupNotes": "THis is a note"
      }
    ]
  }
]