数据在第一个响应中到达时,消除了发送Xmlhttprequest的开销

问题描述

我正在构建一个随机引号生成器,为此,我使用Xmlhttprequest从API获取引号。 当有人单击“生成报价”按钮时,http获取请求将发送到Api,并且每次单击都会显示随机报价。一切对我来说都很好,但唯一的问题是,每次单击我都会发送一个新的http请求,并且我想发送一次请求,然后继续显示响应数据。我尝试在这里使用abort()方法,但仍然遇到一些问题。 somone可以指导我如何达到目标吗?

MY html files looks something like this
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="assets/styles/app.css"> 
    <script src="assets/scripts/xmlhttprequest.js" defer></script>
    <!-- <script src="assets/scripts/app.js"></script> -->

</head>
<body>
    <div id="main">
        <h2 id="heading">Random Quotes Generator</h2>
        <div id="quotes">
            <button class="btn btn-primary btn-lg">Generate Quotes</button>
            </div>
            <div>
               <article></article>
               <p id="authorName"></p>
    </div>
    
        
        
    </div>
</body>
</html>


CSS code

body{

    background-color:darkcyan;
}

#heading{

    font-style: oblique;
    display: flex;
    justify-content: center;
    margin-left: 60px;
   margin-top: 30px;
    
}
#quotes{

    margin-left: 45%;
    margin-top: 50px;
    
    
}
.inner{
    background-color:lightblue;
    border: 0px solid green;
    border-style:groove;
    padding:90px; /*--100*/
    margin-left: 30%;
    margin-top: 50px;
    margin-bottom:20px;
    width:40%;
    font-family:'Segoe UI',Tahoma,Geneva,Verdana,sans-serif;
    font-weight:600;
    font-size: 20px;
    color:saddlebrown;
}

#authorName{
    text-align:right;
    color: lightseagreen;
}


Javascript code -
const button=document.querySelector('button')
const innerQuotesDiv=document.querySelectorAll('div')[2]
const article=innerQuotesDiv.firstElementChild
const authorName=article.nextElementSibling
    
function generateRandomIndex(length){

    console.log(length)
    return (Math.floor(Math.random()*length))
  }

  function getQuotes(){
    
   // console.log(noOfTimesBtnClicked)
    let xhr=new XMLHttpRequest()
    xhr.open('GET','https://type.fit/api/quotes')
    xhr.onload=function(){

      let quotes=JSON.parse(xhr.response)
        console.log(quotes)
        let index=generateRandomIndex(quotes.length)
        innerQuotesDiv.classList.add('inner')
        article.textContent=quotes[index].text 
        if(!quotes[index].author)
       {
           authorName.textContent='Anonymous'  
       }
       else{
        authorName.textContent=quotes[index].author  
       }
    }
    
    xhr.onerror=function(){

      console.log(xhr.response)
      console.log(xhr.status)
      alert('something went wrong')
  }
  xhr.send() 
  
  }

  function abortGetRequest(xhr){
    
    xhr.abort()
  }



  button.addEventListener('click',()=>{

    //console.log('clicked')
    


    getQuotes()

    

})


JS code in which i have tried to use abort() --


const button=document.querySelector('button')
const innerQuotesDiv=document.querySelectorAll('div')[2]
const article=innerQuotesDiv.firstElementChild
const authorName=article.nextElementSibling


function generateRandomIndex(length){

    console.log(length)
    return (Math.floor(Math.random()*length))
  }

  function getQuotes(){
    
   // console.log(noOfTimesBtnClicked)
    let xhr=new XMLHttpRequest()
    xhr.open('GET','https://type.fit/api/quotes')
    xhr.onload=function(){

      let quotes=JSON.parse(xhr.response)
        console.log(quotes)
        let index=generateRandomIndex(quotes.length)
        innerQuotesDiv.classList.add('inner')
        article.textContent=quotes[index].text 
        if(!quotes[index].author)
       {
           authorName.textContent='Anonymous'  
       }
       else{
        authorName.textContent=quotes[index].author  
       }
    }
    
    xhr.onerror=function(){

      console.log(xhr.response)
      console.log(xhr.status)
      alert('something went wrong')
  }
  xhr.send() 
  abortGetRequest(xhr)

  }

  function abortGetRequest(xhr){
    
    xhr.abort()
  }

function displayQuotes(quotes){

  let index=generateRandomIndex(quotes.length)
  innerQuotesDiv.classList.add('inner')
  article.textContent=quotes[index].text 
  if(!quotes[index].author)
 {
     authorName.textContent='Anonymous'  
 }
 else{
  authorName.textContent=quotes[index].author  
 }

}

  button.addEventListener('click',()=>{

    //console.log('clicked')
    


    getQuotes()

   
    

})

使用访存API-我认为引号中没有定义,因为引号在onload函数之前执行。我该如何做到同步或其他任何方式,我都可以使用分配给quote变量的那个诺言中的数据。

const button=document.querySelector('button')
const innerQuotesDiv=document.querySelectorAll('div')[2]
const article=innerQuotesDiv.firstElementChild
const authorName=article.nextElementSibling
let quotes;
// console.log(button)
// console.dir(innerQuotesDiv)
 //console.log(article)
 //console.log(authorName)

 quotes=window.addEventListener('load',fetchApi)
function generateRandomIndex(length){

  console.log(length)
  return (Math.floor(Math.random()*length))
}

function fetchApi(){

   let d=fetch('https://type.fit/api/quotes')
    .then(response=>{
        return response.json()
    })
    .then(data=>{
        console.log(data)
        return data
    })
    console.log(d)
    return d
}




function changeQuotes(){
     
    console.log(quotes)
    let index=generateRandomIndex(quotes.length)
    innerQuotesDiv.classList.add('inner')
    article.textContent=quotes[index].text 
    if(!quotes[index].author)
   {
       authorName.textContent='Anonymous'  
   }
   else{
    authorName.textContent=quotes[index].author  
   }

}
  button.addEventListener('click',()=>{
      
         changeQuotes()
  })

解决方法

我没有测试,但是...

window.addEventListener('DOMContentLoaded',()=>{
    const innerQuotesDiv=document.querySelectorAll('div')[2]
    const article=innerQuotesDiv.firstElementChild
    const authorName=article.nextElementSibling

    function changeQuotes(quotes) {
        console.log(quotes)
        let index = generateRandomIndex(quotes.length)
        innerQuotesDiv.classList.add('inner')
        article.textContent = quotes[index].text
        if (!quotes[index].author) {
            authorName.textContent = 'Anonymous'
        } else {
            authorName.textContent = quotes[index].author
        }
    }

    const request= fetchData('https://type.fit/api/quotes');

    document.querySelector('button').addEventListener('click',()=>{
           request.then(changeQuotes);
    })
})

function generateRandomIndex(length){
    console.log(length)
    return (Math.floor(Math.random()*length))
}

function fetchData(url) {
    return fetch(url)
        .then(response => {
            return response.json()
        })
        .then(data => {
            console.log(data)
            return data
        })
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...