【问题标题】:for() loop not working within 2nd $.getJSON requestfor() 循环在第二个 $.getJSON 请求中不起作用
【发布时间】:2017-07-11 13:43:53
【问题描述】:

背景:我正在尝试提取 JSON 数据来填充职业部分。我在第一个 $.getJSON() 请求中成功请求并提取了 JSON 数据并填充了标题。下一步是提取发布 ID URL 并打开第二个请求以提取描述和应用 URL。

问题:第二个请求有效,因为我可以看到将对象拉入控制台,但由于某种原因,我的循环没有使用描述或 URL 填充该部分。我也没有收到任何控制台错误,这使得查明问题有点困难。它与异步请求有什么关系吗?我是 AJAX、JSON 和 API 的第一次修补。

如果需要一些关于 API 的文档: https://dev.smartrecruiters.com/customer-api/posting-api/

// Create variable to append postings to
var postingsContainer = document.querySelector('div.job-container');

// Creates postings JSON request
$.getJSON('https://api.smartrecruiters.com/v1/companies/SynchronyGroup/postings', function(postings) {

    // Check to see if data is being pulled
    console.log(postings);

    showJobs(postings);

});

// Function that pulls json data and populates careers section
function showJobs(jsonObj) {

    // Variable that holds job postings json data
    var jobs = jsonObj['content']

    // Loop to create open position elements
    for (var i = 0; i < jobs.length; i++) {

        // Creates Column for job postings
        var jobPosting = document.createElement('div')
        jobPosting.setAttribute('class', 'col-12 col-md-6 col-lg-4 my-5 job-posting');

        // Creates Job Title 
        var jobH5 = document.createElement('h5');
        jobH5.textContent = jobs[i].name;

        jobPosting.appendChild(jobH5);
        postingsContainer.appendChild(jobPosting);

        // Store job post IDs in var
        var jobId = jobs[i].ref;

        // Creates post 2nd ID JSON request
        $.getJSON(jobId, function(data) {

            // Check to see if data is being pulled
            console.log(data);

            showDetails(data);

        });

    }
}

//Function for posting description and apply url
function showDetails(data) {

    // Loop to pull company description and apply url, then append to job posting element
    for (var j = 0; j < data.length; j++) {

        console.log("I work");

        // Creates Company Desc. and Apply Link
        var jobDetail = document.createElement('p');
        var jobApply = document.createElement('a');

        jobDetail.textContent = data[j].sections.companyDescription;
        jobApply.setAttribute('href', data[j].applyUrl);
        jobApply.setAttribute('class', 'btn-primary');

        jobPosting.appendChild(jobDetail);
        jobPosting.appendChild(jobApply);

    }
}

【问题讨论】:

  • 你的 jobPosting.appendChild(...) 在你的 showDetails 方法中。此范围内不存在此变量。
  • 您的问题在于var jobs = jsonObj['content'] 这一行。将行更改为var jobs = jsonObj.content;,因为content 是一个对象而不是数组

标签: jquery json ajax api


【解决方案1】:

您的主要问题是 jobPosting var 的值。

此变量在每次循环迭代时在 showJobs 函数中创建,但您永远不会将此变量传递给 showDetails 函数。

因为这个变量是在每次迭代时创建的,所以您需要确保传递正确的值(有关更多信息,您可以查看 js closure 及其工作原理)。在您的情况下,因为 $.getJSON(jobId, function(data) { 您不能简单地使用变量名。如果是这样,您将传递最后一个值:您在末尾拥有的值循环。这意味着您需要关闭上下文。

为了实现这一点,您可以使用 IIFE。有关这方面的更多信息,您可以参考这个问题:What is the (function() { } )() construct in JavaScript?

例子:

// Create variable to append postings to
var postingsContainer = document.querySelector('div.job-container');

// Creates postings JSON request
$.getJSON('https://api.smartrecruiters.com/v1/companies/SynchronyGroup/postings', function (postings) {

    // Check to see if data is being pulled
    //console.log(postings);

    showJobs(postings);

});

// Function that pulls json data and populates careers section
function showJobs(jsonObj) {

    // Variable that holds job postings json data
    var jobs = jsonObj['content']

    // Loop to create open position elements
    for (var i = 0; i < jobs.length; i++) {

        // Creates Column for job postings
        var jobPosting = document.createElement('div');
        jobPosting.setAttribute('class', 'col-12 col-md-6 col-lg-4 my-5 job-posting');

        // Creates Job Title
        var jobH5 = document.createElement('h5');
        jobH5.textContent = jobs[i].name;

        jobPosting.appendChild(jobH5);
        postingsContainer.appendChild(jobPosting);

        // Store job post IDs in var
        var jobId = jobs[i].ref;

        //
        //
        // IIFE
        (function (jobPosting) {
            // Creates post 2nd ID JSON request
            $.getJSON(jobId, function (data) {

                // Check to see if data is being pulled
                //console.log(data);

                showDetails(data, jobPosting);

            })
        }(jobPosting));

    }
}
//Function for posting description and apply url
function showDetails(data, jobPosting) {

    // Loop to pull company description and apply url, then append to job posting element
    //for (var j = 0; j < data.length; j++) {

    //console.log("I work");

    // Creates Company Desc. and Apply Link
    var jobDetail = document.createElement('p');
    var jobApply = document.createElement('a');

    jobDetail.textContent = 'showDetails: ' + data.company.name;
    jobApply.setAttribute('href', data.applyUrl);
    jobApply.setAttribute('class', 'btn-primary');

    jobPosting.appendChild(jobDetail);
    jobPosting.appendChild(jobApply);

    //}
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>



<div class="job-container"></div>

【讨论】:

  • 我看到你评论了第二个循环,这是因为使用 IIFE 时不需要 for() 吗?
  • @WeebleWobb 不,抱歉,我在第二个(内部)getJson 中评论了循环,因为该变量是一个普通对象,您不能像数组一样循环。您可以对 for(key in data) 或类似的对象使用不同的循环策略。谢谢
  • 好的,感谢您分享额外的 IIFE 线程。有点要掌握,但它看起来很有效。必须成为我继续修补的东西才能让自己更舒服,但这是朝着正确方向迈出的一步。
  • @WeebleWobb 我为你感到高兴。非常感谢
【解决方案2】:

签出这个工作代码只需要更改这一行var jobs = jsonObj['content']。换行为var jobs = jsonObj.content;

// Create variable to append postings to
var postingsContainer = document.querySelector('div.job-container');

// Creates postings JSON request
$.getJSON('https://api.smartrecruiters.com/v1/companies/SynchronyGroup/postings', function(postings) {

    // Check to see if data is being pulled
    //console.log(postings);

    showJobs(postings);

});

// Function that pulls json data and populates careers section
function showJobs(jsonObj) {

    // Variable that holds job postings json data
    var jobs = jsonObj.content;

    // Loop to create open position elements
    for (var i = 0; i < jobs.length; i++) {

        // Creates Column for job postings
        var jobPosting = document.createElement('div')
        jobPosting.setAttribute('class', 'col-12 col-md-6 col-lg-4 my-5 job-posting');

        // Creates Job Title 
        var jobH5 = document.createElement('h5');
        jobH5.textContent = jobs[i].name;

        jobPosting.appendChild(jobH5);
        postingsContainer.appendChild(jobPosting);

        // Store job post IDs in var
        var jobId = jobs[i].ref;

        // Creates post 2nd ID JSON request
        $.getJSON(jobId, function(data) {

            // Check to see if data is being pulled
            //console.log(data);

            showDetails(data);

        });

    }
}

//Function for posting description and apply url
function showDetails(data) {

    // Loop to pull company description and apply url, then append to job posting element
    for (var j = 0; j < data.length; j++) {

        console.log("I work");

        // Creates Company Desc. and Apply Link
        var jobDetail = document.createElement('p');
        var jobApply = document.createElement('a');

        jobDetail.textContent = data[j].sections.companyDescription;
        jobApply.setAttribute('href', data[j].applyUrl);
        jobApply.setAttribute('class', 'btn-primary');

        jobPosting.appendChild(jobDetail);
        jobPosting.appendChild(jobApply);

    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="job-container"></div>

【讨论】:

    猜你喜欢
    • 2020-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-17
    • 1970-01-01
    相关资源
    最近更新 更多