将多个ajax请求循环到一个返回中

时间:2019-05-17 14:18:39

标签: javascript arrays json ajax

所以我试图从两个AJAX请求中返回一些值。

我目前正在做的是调用两个请求,将它们传递到变量中,然后尝试将数据附加到HTML ID上。

我在这里遇到一些问题,主要是我似乎只能传递一组数据,而不能传递全部数据。

所以我们说

$.each(data1, function(data1, data2) {
  console.log(JSON.stringify(data1.name));
  console.log(JSON.stringify(data2.name));

  $(jobPositions).append('\
    <span>' + data1.name + '</span>\
    <span>' + data2.name + '</span>\
  ');
});

data1的数据显示所有名称,而不显示data2的名称。

这是完整的代码:

<script>
  (function() {
    const jobPositions = document.getElementById('jobPositions');

    var jobs = $.ajax({
      url : 'https://www.welcomekit.co/api/v1/external/jobs?access_token=REDAC&organization_reference=REDAC&websites=true&status=published',
      dataType: 'json'
    });

    var jobDepartments = $.ajax({
      url: 'https://www.welcomekit.co/api/v1/external/departments?access_token=REDAC&organization_reference=REDAC',
      dataType: 'json'
    });

    $.when(jobs, jobDepartments).done(function(jobs, jobDepartments) {
      var data1 = jobs[0];
      var data2 = jobDepartments[0];

      $.each(data1, function(data1, data2) {
        console.log(JSON.stringify(data1.name));
        console.log(JSON.stringify(data2.name));

        $(jobPositions).append('\
          <span>' + data1.name + '</span>\
          <span>' + data2.name + '</span>\
        ');
      });
    });
  })();
</script>

是否可以同时传递两组数据,以便我可以遍历所有数据?

更新

这是每个JSON输出的快速浏览

工作(数据1)

[
    {
        "reference": "ARTIF_W4WN5Ll",
        "name": "Product Owner",
        "organization_reference": "pDgj5zr",
        "profession_reference": "technical_project_management",
        "company_description": "",
        "description": "**Your mission**\r\n\r\n* As a Product Owner, you will be responsible for maintaining Artifakt App roadmap and product functionalities.  \r\n* Within your squad (small cross functional team), you will also define new features aligned with market and business needs\r\n* You will work in close collaboration with Artifakt users, Sales, Marketing and R&D Teams.\r\n\r\n**Your responsabilities**\r\n\r\n* Define Artifakt functionalities with Product Manager and Product Designer and maintain your squad’s roadmap.\r\n* Interact with users, market analysts and sales to make sure of the product / market fit.\r\n* Analyze preferences and requests of Artifakt users to ensure high quality user experience.\r\n* Incorporate feature requests into product roadmap.\r\n* Maintain and prioritize backlog.\r\n* Schedule and coordinate sprints, set sprint goals.\r\n* Schedule releases and upgrades.\r\n* Write user stories and define acceptance criteria.\r\n* Test new features to ensure product quality and make product demonstrations.\r\n* Ensure Artifakt roadmap visibility and internal & external reporting.\r\n* Analyze the impact and results of each major feature (experience with data analysis tools such as Google Analytics, Amplitude or Segment).\r\n* Keep track on industry trends (strategic monitoring).",
        "profile": "* Proven experience as a Product Owner for a B2B market is a plus\r\n* Excellent analytical ability (but don’t overanalyze) and experience in transforming business requirements into effective product design and delivering end-to-end user experience solutions\r\n* You are super autonomous but you also know how to work in a team  (team spirit, good communication abilities, etc.)\r\n* Strong experience in Agile process and principles (SCRUM, KANBAN, etc.)\r\n* Technical / Coding background is a plus\r\n* Interest in Cloud solutions (AWS, Microsoft Azure, GCP…) is a plus\r\n* You speak / write in English with good standards\r\n* Problem-solving attitude\r\n* “Best for now” instead of perfection (“doer”)\r\n\r\nReady to taking up challenges? Join us!",
        "recruitment_process": "",
        "contract_type": "FULL_TIME",
        "language": "en",
        "salary": {
            "min": null,
            "max": null,
            "currency": "EUR",
            "period": "none"
        },
        "is_remote": false,
        "contract_duration_min": null,
        "contract_duration_max": null,
        "department_id": 10894,
        "education_level": "BAC_5",
        "experience_level": "2_TO_3_YEARS",
        "apply_url": null,
        "start_date": "2019-04-01T00:00:00.000+02:00",
        "external_reference": null,
        "status": "published",
        "office_id": 13983,
        "websites": [
            {
                "reference": "lafayette-plug-and-play",
                "name": "Lafayette Plug and Play",
                "url": "https://lafayette-plug-and-play.welcomekit.co/companies/artifakt/jobs/product-owner_paris"
            },
            {
                "reference": "artifakt",
                "name": "Artifakt",
                "url": "https://artifakt.welcomekit.co/jobs/product-owner_paris"
            },
            {
                "reference": "wttj_fr",
                "name": "Welcome to the Jungle",
                "url": "https://www.welcometothejungle.co/companies/artifakt/jobs/product-owner_paris"
            }
        ],
        "created_at": "2019-03-26T16:32:35.848+01:00",
        "updated_at": "2019-03-28T10:25:04.967+01:00",
        "published_at": "2019-03-28T10:25:04.956+01:00",
        "archived_at": null
    },
    {
        "reference": "ARTIF_p2gVpOW",
        "name": "Cloud Platforms Expert (DevOps)",
        "organization_reference": "pDgj5zr",
        "profession_reference": "devops",
        "company_description": "",
        "description": "**Your mission**\r\n\r\n* Artifakt Platforms Team (part of our R&D Team) is building and maintaining Artifakt Cloud platforms. \r\n* As a part of the Platforms Team, you core mission will be to create most performant and robust Cloud platforms. \r\n* You will be also responsible for the quality of the built and deployed platforms.\r\n\r\n**Your responsabilities **\r\n\r\n* Design & build on a daily basis resilient and scalable platforms for multiple Cloud providers.\r\n* Support internal and external customers on their platforms: keep them always up and running.\r\n* Providing guidance and recommendations to increase customer platforms efficiency and performance (reduced Build & Run actions time).\r\n* Reduce platforms incidents: monitoring, training. \r\n* Keep accurate records and document actions (platforms documentation for users, landing pages).\r\n* Communicate with Artifakt users and other Teams to increase user satisfaction (demos, blog posts, meetups, sharing KPIs).\r\n",
        "profile": "* Proven DevOps experience\r\n* Cloud expertise (AWS or Azure or Alibaba or...)\r\n* Mastering languages and tools of our tech stack\r\n* Proficient in leveraging CI/CD tools to automate testing and deployment \r\n* Experience with the agile methodology \r\n* A team-player, flexible and able to work in a fast-paced environment\r\n* Ability to understand users expectations to challenge and build platforms that perfectly suit our customer business needs\r\n\r\n**Want to?**\r\n\r\n* Learn fast and be challenged every working day.\r\n* Work with passionate tech people.\r\n* Progress in an Agile and fast-paced environment.\r\n\r\nJoin us!",
        "recruitment_process": "* RH interview (Video call, 45 min)\r\n* On-site interview - Technical test\r\n* Reference check\r\n* Final interview with both founders\r\n* Coffee with the Artifakt team \r\n* Offer!!!",
        "contract_type": "FULL_TIME",
        "language": "en",
        "salary": {
            "min": 45000,
            "max": 48000,
            "currency": "EUR",
            "period": "yearly"
        },
        "is_remote": false,
        "contract_duration_min": null,
        "contract_duration_max": null,
        "department_id": 10894,
        "education_level": "BAC_5",
        "experience_level": "3_TO_4_YEARS",
        "apply_url": null,
        "start_date": "2019-06-01T00:00:00.000+02:00",
        "external_reference": null,
        "status": "published",
        "office_id": 13983,
        "websites": [
            {
                "reference": "lafayette-plug-and-play",
                "name": "Lafayette Plug and Play",
                "url": "https://lafayette-plug-and-play.welcomekit.co/companies/artifakt/jobs/test_paris"
            },
            {
                "reference": "artifakt",
                "name": "Artifakt",
                "url": "https://artifakt.welcomekit.co/jobs/test_paris"
            },
            {
                "reference": "wttj_fr",
                "name": "Welcome to the Jungle",
                "url": "https://www.welcometothejungle.co/companies/artifakt/jobs/test_paris"
            }
        ],
        "created_at": "2019-03-22T17:12:28.177+01:00",
        "updated_at": "2019-05-13T13:56:42.376+02:00",
        "published_at": "2019-03-28T10:24:47.682+01:00",
        "archived_at": null
    },
]

工作部门(数据2)

[
    {
        "id": 10897,
        "name": "Customer Support / Success ",
        "is_active": true,
        "slug": "customer-support-success",
        "description": null
    },
    {
        "id": 10893,
        "name": "G&A",
        "is_active": true,
        "slug": "g-a",
        "description": null
    },
    {
        "id": 10896,
        "name": "Marketing",
        "is_active": true,
        "slug": "marketing",
        "description": null
    },
    {
        "id": 10894,
        "name": "R&D",
        "is_active": true,
        "slug": "r-d",
        "description": null
    },
    {
        "id": 10895,
        "name": "Sales",
        "is_active": true,
        "slug": "sales",
        "description": null
    }
]

更新2

所以我大部分使用以下方法来工作

<script>
  (function() {
    const jobPositions = document.getElementById('jobPositions');

    var jobs = $.ajax({
      url : 'https://www.welcomekit.co/api/v1/external/jobs?access_token=redac&organization_reference=redac&websites=true&status=published',
      dataType: 'json'
    });

    var jobDepartments = $.ajax({
      url: 'https://www.welcomekit.co/api/v1/external/departments?access_token=redac&organization_reference=redac',
      dataType: 'json'
    });

    $.when(jobs, jobDepartments).done(function(jobs, jobDepartments) {
      var data1 = jobs[0];
      var data2 = jobDepartments[0];

      $.each(data1, function(i, item) {
        var start = i++;

        console.log(data2[i]);

        if(start) {
          $(jobPositions).append('\
          <a target="_blank" href="'+ item.websites[1].url +'" class="jobPosition-item d-md-flex justify-content-between align-items-center flex-wrap">\
            <div>\
              <span class="jobPositions-name">' + item.name + '</span>\
            </div>\
            <div class="right right-info d-flex align-items-center">\
              <span class="jobPositions-profession">' + data2[i].name + '</span>\
              <div class="d-flex">\
                <img src="/hubfs/www/about/white-icon-arrow.png" height="11" width="11" alt="arrow">\
              </div>\
            </div>\
          </a>\
        ');
        }
      });
    });
  })();
</script>

是否可以在两个响应之间匹配ID?部门,这样我就可以为每个工作输出正确的部门。

2 个答案:

答案 0 :(得分:0)

我建议使用Map作为部门的查找表,并以其ID为键。与问题无关,但是我更喜欢在创建新元素时使用jQuery:

// Create a Map for the departments:
const departmentMap = new Map(data2.map(item => [item.id, item]));

for (const item of data1) {
    // Use jQuery to the full:
    jobPositions.append(
        $("<a>", { target: "_blank", href: item.websites[1].url })
            .addClass("jobPosition-item d-md-flex justify-content-between align-items-center flex-wrap")
            .append(
                $("<div>").append($("<span>").addClass("jobPositions-name").text(item.name)),
                $("<div>").addClass("right right-info d-flex align-items-center").append(
                    $("<span>").addClass("jobPositions-profession").text(departmentMap.get(item.department_id).name),
                    $("<div>").addClass("d-flex").append(
                        $("<img>", { src: "/hubfs/www/about/white-icon-arrow.png", height:11, width:11, alt:"arrow" })
                    )
                )
            )
    );
}

答案 1 :(得分:0)

我使用以下方法进行了这项工作:

<script>
  (function() {
    const jobPositions = document.getElementById('jobPositions');

    var jobs = $.ajax({
      url : 'https://www.welcomekit.co/api/v1/external/jobs?access_token=redac&organization_reference=redac&websites=true&status=published',
      dataType: 'json'
    });

    var jobDepartments = $.ajax({
      url: 'https://www.welcomekit.co/api/v1/external/departments?access_token=redac&organization_reference=redac',
      dataType: 'json'
    });

    $.when(jobs, jobDepartments).done(function(jobs, jobDepartments) {
      var data1 = jobs[0];
      var data2 = jobDepartments[0];

      $.each(data1, function(i, item) {
        var start = i++;
        var job = data2.find(d => d.id === item.department_id);

        if(job) {
            var jobID = job.id;
        }

        if(start) {
          $(jobPositions).append('\
          <a target="_blank" href="'+ item.websites[1].url +'" class="jobPosition-item d-md-flex justify-content-between align-items-center flex-wrap">\
            <div>\
              <span class="jobPositions-name">' + item.name + '</span>\
            </div>\
            <div class="right right-info d-flex align-items-center">\
              <span class="jobPositions-profession">' + job.name + '</span>\
              <div class="d-flex">\
                <img src="/hubfs/www/about/white-icon-arrow.png" height="11" width="11" alt="arrow">\
              </div>\
            </div>\
          </a>\
        ');
        }
      });
    });
  })();
</script>