【发布时间】: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是一个对象而不是数组