将两个GET Rest API的结果合并到一个JSON列表中

时间:2018-02-01 13:46:16

标签: jquery json ajax rest

我目前仍在尝试合并来自两个GET REST API调用的两个JSON列表。

第一个API调用会抓取尝试访问该网页的用户的userID。

后两个url每个都返回一个特定安全组中的userID列表。 我需要一个列表,将两个JSON列表的值合并到一个列表中。

如果正在访问网页的用户ID不在 安全组中的用户ID列表中,则页面内容将对其隐藏。用户只需要位于两个安全组中的一个中即可访问该网页。

我到目前为止所做的尝试使用户需要在两个安全组中进行访问,而他们确实只需要一个。我可能会以错误的方式解决这个问题。这可以变成if elseif语句吗?有任何想法吗?

var submitterId = null;
    var userIdUrl = '/api/HttpCurrentUser';
    var Url1 = '/api/ActiveDirectoryMembers/example1';
    var Url2 = '/api/ActiveDirectoryMembers/example2';
    $("#masterContainer").hide();
    $.get(userIdUrl).done(function (result) {
        submitterId = result;
        isInGroup = false;
        $.get(Url1).done(function (result) {
            result.forEach(function (item) {
                if (item == submitterId) {
                    $("#masterContainer").show();
                    isInGroup = true;
                }
            });
            if (!isInGroup) {
                $("#masterContainer").replaceWith("Access to this site is restricted to the example1 and example2 groups);
            }
        });
        $.get(Url2).done(function (result) {
            result.forEach(function (item) {
                if (item == submitterId) {
                    $("#masterContainer").show();
                    isInGroup = true;
                }
            });
            if (!isInGroup) {
                $("#masterContainer").replaceWith("Access to this site is restricted to example 1 and example 2 groups");
            }
        });

        });

1 个答案:

答案 0 :(得分:0)

修改了您的代码,并在编辑中添加了评论:

var submitterId = null;
    var userIdUrl = '/api/HttpCurrentUser';
    var Url1 = '/api/ActiveDirectoryMembers/example1';
    var Url2 = '/api/ActiveDirectoryMembers/example2';
    var mergedResult; // a variable to hold both results
    $("#masterContainer").hide();
    $.get(userIdUrl).done(function (result) {
      submitterId = result;
      isInGroup = false;
      $.get(Url1).done(function (result) {
        mergedResult = result;
      });
      $.get(Url2).done(function (result) {
        $.extend(mergedResult, result); // will merge the result, into mergedResult (the first target)
      });

      mergedResult.forEach(function (item) {
        if (item == submitterId) {
          $("#masterContainer").show();
          isInGroup = true;
        }
      });

      if (!isInGroup) {
        $("#masterContainer").replaceWith("Access to this site is restricted to example 1 and example 2 groups");
      }

    });

基本上,使用extend合并结果。