Нужна помощь по запросу AJAX - PullRequest
0 голосов
/ 24 декабря 2018

я впервые работаю с $.ajax requests, в настоящее время я создаю каталог сотрудников, в котором должно быть 12 случайных людей, таких как:

Employee Gallery Mockup

Я создал 12 карт галереи динамически, $ gallery Markup представляет каждую карту

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.log(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);  
  }); 
} 
}); 

, поэтому мой вопрос: как добавить больше карточек сотрудников, не копируя каждую деталь?В настоящее время я могу получить это:

Every picture is the same

также для справки, это репо моего проекта https://github.com/SpaceXar20/FSJS-techdegree-project-5, У меня есть свой ajaxзапрос в строке 119 app.js, кто-нибудь может помочь?

Ответы [ 2 ]

0 голосов
/ 24 декабря 2018

Здравствуйте, попробуйте следующий скрипт

0 голосов
/ 24 декабря 2018

Вы можете добавить свой шаблон карточки так:

$.ajax({
    url: 'https://randomuser.me/api/?nat=us&results=12&',
    dataType: 'json',
    success: function (data) {
        console.log(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
    }

})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...