简体   繁体   中英

How can i display both the fetched data from an external api and from local storage on the same card in html using javascript

I need help by editing my code on how i can be able to display the data i have fetched from an external api and that from a local json file so that my card can show the user's avatar,name,occcupation,total number of impressions and total number of conversions on the same card.

Here is my code:

<script>
        
        fetch("https://api.airtable.com/v0/appBTaX8XIvvr6zEC/tblYPd5g5k5IKIc98?api_key=key4v56MUqVr9sNJv")
      
            .then((data)=>{
               // console.log(data)
               return data.json();

            })
            .then ((completedata)=>{
             //console.log(completedata.records[0])
             //an empty variable to catch the incoming data
             let data1="";
             // Then i added a html template to the data1 variable
               completedata.records.forEach((values)=>{
                data1+=` 
                <div class="card">
                    <span class="avatarLetter">${values.fields.Name.substr(0,1)}</span>
                    <p class="name">${values.fields.Name}</p>
                    <p class="occupation">${values.fields.occupation}</p>
             </div> `;
               });

               document.querySelector("#card").innerHTML=data1;
            })

            
            .catch((error)=>{
             console.log(error);

            })
    //pulling data from local json file
    fetch('./logs.json')
  .then((response) => {
    return response.json();
  })
  .then((data) => {
    // console.log(data);
    let data1 = "";
  let totalImpressions = 0;
  let totalConversions = 0;
    data.forEach((values) => {
      totalImpressions += values.impression;
      totalConversions += values.conversion;
      data1 += ` 
            <div class="card">
            <p class="impression">${values.impression}</p>
            <p class="conversion">${values.conversion}</p>
            </div> `;
    });
    data1 += `<div>Total impressions = ${totalImpressions} Total conversions = ${totalConversions}</div>`;
    document.querySelector("#card").innerHTML = data1;

  })
  .catch((error) => {
    console.log(error);
  })

        </script>

When you write second time

document.querySelector("#card").innerHTML = data1;

you overwrite #card content.

The right way:

document.querySelector("#card").innerHTML += data1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM