Я впервые работаю с $.ajax requests, в настоящее время я создаю каталог сотрудников, который должен получить 12 случайных людей вроде этого:
Я создал 12 карточек галереи динамически, разметка $ gallery представляет каждую карточку.
var $galleryMarkUp = $('<div class = "card"> </div>');
var $cardIMGContainer = $('<div class = "card-img-container"> </div>');
var $cardInfoContainer = $('<div class = "card-info-container"> </div>');
//Append $cardIMGContainer and $cardInfoContainer inside $galleryMarkUp
$galleryMarkUp.append($cardIMGContainer, $cardInfoContainer);
//I append an img src inside $cardIMGContainer
$cardIMGContainer.prepend('<img class = "card-img" src = "https://placehold.it/90x90" alt = "profile picture">');
//I also need to append an h3 and a couple of paragraphs inside $cardInfoContainer
$cardInfoContainer.prepend('<h3 id = "name" class = "card-name cap">first last</h3>',
'<p class = "card-text">email</p>', '<p class = "card-text cap">city, state</p>');
//Append $galleryMarkUp inside <div id = "gallery" class = "gallery">
$('#gallery').append($galleryMarkUp);
/ * Я использовал цикл, чтобы клонировать их 12 раз * /
for (let index = 0; index <11; index++) {
$galleryMarkUp.clone().insertAfter($galleryMarkUp)
ниже мой запрос ajax, который я сделал для url: 'https://randomuser.me/api/?nat=us&results=12&'
$.ajax({
url: 'https://randomuser.me/api/?nat=us&results=12&',
dataType: 'json',
success: function(data) {
console.info(data); //this should log the data for 12 employees in JSON format
var employeeInfo = data.results //creating a reference to data.results
$.each(employeeInfo, function(index, employee) {
//create variable references for Name, email, city,state, etc
var name = employee.name.first + " " + employee.name.last;
var email = employee.email;
var picture = employee.picture.large;
var location = employee.location.city;
var number = employee.phone;
var fullStreet = employee.location.street + " " + location + " " + employee.location.postcode;
var birthday = employee.dob.date;
//SHOW CONTENT FOR SMALL GALLERY CARDS
//attach images to employee gallery
$('.card-img').attr('src', picture);
//Get to display the name, I used a code snippet from https://stackoverflow.com/a/11468183/10043628 by user jagm
$('.card-info-container > :first-child').text(name);
//Get to display email
$('.card-text').text(email);
//Get to display city and state
$('.card-info-container > :nth-child(3)').text(location);
//SHOW CONTENT FOR MODAL BOXES
//display name
$('.modal > :nth-child(2)').text(name);
//attach images to employee modals
$('.modal-img').attr('src', picture);
//Display email
$('.modal > :nth-child(3)').text(email);
//Display city
$('.modal > :nth-child(4)').text(location);
//Display number
$('.modal > :nth-child(6)').text(number);
//Display address
$('.modal > :nth-child(7)').text(fullStreet);
//Display Birthday
$('.modal > :nth-child(8)').text(birthday);
});
}
});
Итак, мой вопрос: как мне добавить больше карточек сотрудников, не копируя каждую деталь? В настоящее время я могу получить это:
также для справки, это репо моего проекта https://github.com/SpaceXar20/FSJS-techdegree-project-5, у меня есть запрос ajax в строке 119 app.js, может ли кто-нибудь помочь?
На самом деле, вызов ajax кажется правильным, не могли бы вы проверить с помощью метода API проблемы.
Вы используете объект json из запроса Ajax и проходите через него. Замените имена и URL изображения данными из json. И клонирование не упростит. Вам нужно воссоздать каждую собаку в петле.



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Вы можете добавить свой шаблон карты следующим образом:
$.ajax({
url: 'https://randomuser.me/api/?nat=us&results=12&',
dataType: 'json',
success: function (data) {
console.info(data); //this should log the data for 12 employees in JSON format
var employeeInfo = data.results //creating a reference to data.results
var _cardTemplate = '';
$.each(employeeInfo, function (index, employee) {
//create variable references for Name, email, city,state, etc
var name = employee.name.first + " " + employee.name.last;
var email = employee.email;
var picture = employee.picture.large;
var location = employee.location.city;
var number = employee.phone;
var fullStreet = employee.location.street + " " + location + " " + employee.location.postcode;
var birthday = employee.dob.date;
//SHOW CONTENT FOR SMALL GALLERY CARDS
_cardTemplate += '<div class = "card">';
_cardTemplate += '<div class = "card-img-container">';
_cardTemplate += '<img class = "card-img" src= "' + picture + '" alt = "profile picture"></div>';
_cardTemplate += '<div class = "card-info-container"><h3 id = "name" class = "card-name cap">' + name + '</h3>';
_cardTemplate += '<p class = "card-text">' + email + '</p><p class = "card-text cap">' + location + '</p>';
_cardTemplate += '</div></div>';
//SHOW CONTENT FOR MODAL BOXES
//display name
$('.modal > :nth-child(2)').text(name);
//attach images to employee modals
$('.modal-img').attr('src', picture);
//Display email
$('.modal > :nth-child(3)').text(email);
//Display city
$('.modal > :nth-child(4)').text(location);
//Display number
$('.modal > :nth-child(6)').text(number);
//Display address
$('.modal > :nth-child(7)').text(fullStreet);
//Display Birthday
$('.modal > :nth-child(8)').text(birthday);
});
$('#gallery').append(_cardTemplate); //Append Finally all cards with employee details
}
})
Здравствуйте, попробуйте ниже скрипт
Демо-ссылки: https://output.jsbin.com/wijaniwaxo
Вы можете проверить исходный код приведенной выше демонстрации
$(document).ready(function ()
{
var html;
$.ajax({
method: 'get',
dataType: 'json',
url: "https://randomuser.me/api/?nat=us&results=12",
beforeSend: function ()
{
$('.gallery').html('<h1 class = "text-center">Please wait content loading...</h1>');
},
success: function (response)
{
html = '';
if (response.results)
{
$.each(response.results, function (index, value)
{
html += '<div class = "col-md-4 custom-col">';
html += '<img src = "' + value.picture.medium + '" alt = "Image ' + index + '" style = "width: 100px;" />';
html += '<p>' + value.name.first + ' ' + value.name.last + '</p>';
html += '<p>' + value.email + '</p>';
html += '<p>' + value.location.city + '</p>';
html += '</div>';
});
$('.gallery').html(html);
}
},
complete: function (response){}
});
});
Спасибо, это очень помогло
Как и откуда вы получаете контент и заполняете карточку? Вы упомянули об использовании ajax, но я не вижу в вашем коде запроса ajax.