简体   繁体   English

我想将所有 api 结果打印到页面

[英]I Want To Print all the api result to page

I Have This Result Of API我有 API 的这个结果

I Want To access all the values inside this array but when i try for loop or forEach loop its just print the last 9th item of the array我想访问这个数组中的所有值,但是当我尝试 for 循环或 forEach 循环时,它只打印数组的最后 9 项

Just Like This像这样

const options = {
        method: 'GET',
        headers: {
            'X-RapidAPI-Key': 'API-key',
            'X-RapidAPI-Host': 'contextualwebsearch-websearch-v1.p.rapidapi.com'
        }
    };
    
    fetch(`https://contextualwebsearch-websearch-v1.p.rapidapi.com/api/Search/WebSearchAPI?q=${query}&pageNumber=1&pageSize=10&autoCorrect=true`, options)
        .then(response => response.json())
        .then(response => {
            
             for(let i = 0; i < response.value.length; i++){
                result = `
                
                <h3>${response.value[i].title}</h3>
                
                `;
                document.getElementById("result").innerHTML = result;
             }






            //  response.value.forEach(res => {
            //      result = `
            //      <h3><a href="${res.url}">${res.title}</a></h3><br><a href="${res.url}" color="#bdc1c6">${res.url}</a><br>
            //      <p>${res.snippet}</p>
            //      `
            //      document.getElementById("result").innerHTML = result;
            //  ;
            //  });
            console.log(response.value)})
        .catch(err => console.error(err));
})

this is what i was trying please tell me if my code is wrong or give me an appropriate answer这就是我正在尝试的,请告诉我我的代码是否错误或给我一个适当的答案

this is probably your problem:这可能是你的问题:

document.getElementById("result").innerHTML = result;

here you are overriding the value inside after each loop, that's why you will only find the last value displayed.在这里,您将在每次循环后覆盖内部的值,这就是为什么您只会找到显示的最后一个值的原因。

you can use the += operator to increment the HTML to the existing one inside your result element.您可以使用+=运算符将 HTML 递增到result元素中的现有内容。

document.getElementById("result").innerHTML += result;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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