简体   繁体   English

我的 api 中的数据不会显示在我的 html 中(我还是编码新手,但这是我的代码)

[英]My data from my api won't display in my html (im still new to coding but here is my code)

var listApi = document.querySelector(".list-item")
var searchApi = document.getElementById("search-api")
document.querySelector("#enter").addEventListener("click", e => {
    e.preventDefault();
    var inputValue = searchApi.value; 
    fetch('https://wft-geo-db.p.rapidapi.com/v1/geo/cities/'     +inputValue, options)
    .then(response => response.json())
    .then(response => console.log(response))
    .then((data) => {
        var title = document.createElement("li")
        title.setAttribute = ".list-item";
        title.innerText = data;
    })
    .catch(err => console.error(err));

});

//Html portion //HTML部分

<h2 class="justify-center flex">Results</h2>
<ul id="result-list">
  <li class="list-item "></li>

</ul>

The api works fine as it displays the data in the console, i just can figure how to get it in my html. api 在控制台中显示数据时工作正常,我只是想知道如何在我的 html 中获取它。

When you create an element with document.createElement it exists only in memory-- it isn't actually attached to the DOM yet.当您使用document.createElement创建一个元素时,它只存在于内存中——它实际上还没有附加到 DOM。 You need to insert it somewhere, like so:您需要将它插入某处,如下所示:

var listApi = document.querySelector(".list-item")
var searchApi = document.getElementById("search-api")
document.querySelector("#enter").addEventListener("click", e => {
    e.preventDefault();
    var inputValue = searchApi.value; 
    fetch('https://wft-geo-db.p.rapidapi.com/v1/geo/cities/'     +inputValue, options)
    .then(response => response.json())
    .then(response => console.log(response))
    .then((data) => {
        var title = document.createElement("li")
        title.setAttribute = ".list-item"
        title.innerText = data;
        var list = document.getElementById("result-list");
        list.appendChild(title);
    })
    .catch(err => console.error(err));

});

Also note your line title.setAttribute = ".list-item" won't work as you expect-- you are overwriting the setAttribute function with a string.另请注意,您的行title.setAttribute = ".list-item"不会像您预期的那样工作——您正在用字符串覆盖setAttribute function。 Better to just use classList as title.classList.add('list-item');最好只使用classList作为title.classList.add('list-item');

Also , as user Andy points out in the comments, you have another problem with your chaining of .then s-- specifically, you have a .then() that console.log s the result and returns nothing.此外,正如用户 Andy在评论中指出的那样,您的.then链接还有另一个问题——具体来说,您有一个 .then .then() console.log是结果并且不返回任何内容。 The way promise chains work is that the next .then will act on the result passed from the previous .then ; promise 链的工作方式是下一个.then将作用于前一个.then传递的结果; however, .then(response => console.log(response)) will return undefined , so the data argument coming into your next .then will be undefined .但是, .then(response => console.log(response))将返回undefined ,因此进入下一个.thendata参数将是undefined Below is a code example that fixes both the setAttribute issue and the .then issue:下面是修复setAttribute问题和.then问题的代码示例:

var listApi = document.querySelector(".list-item")
var searchApi = document.getElementById("search-api")
document.querySelector("#enter").addEventListener("click", e => {
    e.preventDefault();
    var inputValue = searchApi.value; 
    fetch('https://wft-geo-db.p.rapidapi.com/v1/geo/cities/'     +inputValue, options)
    .then(response => response.json())
    .then(response => {
        console.log(response);
        return response;
    })
    .then((data) => {
        var title = document.createElement("li")
        title.classList.add("list-item");
        title.innerText = data;
        var list = document.getElementById("result-list");
        list.appendChild(title);
    })
    .catch(err => console.error(err));

});

Finally, if you are just attempting to insert a plain object or array as text into the DOM you will likely get unexpected results, such as it displaying simply as "object Object" in the <li> .最后,如果您只是试图将一个普通的 object 或数组作为文本插入到 DOM 中,您可能会得到意想不到的结果,例如它在<li>中仅显示为"object Object" Let's presume for a moment that your response looks something like this:让我们暂时假设您的响应如下所示:

{
    data: ['MacReady', 'Childs', 'Blair', 'Nauls', 'Clark', 'Palmer']
}

To write this data to the DOM, you'd need to access it at the data property, then map over it (either with a loop or using an array method like .forEach ) and add each item to an element (like an <li> in your case) and insert it to the DOM.要将此数据写入 DOM,您需要在data属性中访问它,然后在其上访问 map(使用循环或使用数组方法,如.forEach )并将每个项目添加到一个元素(如<li>在你的情况下)并将其插入 DOM。 Here's an example:这是一个例子:

var listApi = document.querySelector(".list-item")
var searchApi = document.getElementById("search-api")
document.querySelector("#enter").addEventListener("click", e => {
    e.preventDefault();
    var inputValue = searchApi.value; 
    fetch('https://wft-geo-db.p.rapidapi.com/v1/geo/cities/'     +inputValue, options)
    .then(response => response.json())
    .then(response => {
        console.log(response);
        return response;
    })
    .then((data) => {
        let myList = data.data;

        myList.forEach(datum => {
            var title = document.createElement("li")
            title.classList.add("list-item");
            title.innerText = datum;
            var list = document.getElementById("result-list");
            list.appendChild(title);
        });
    })
    .catch(err => console.error(err));

});

There are other approaches to this-- using a for loop, or using DOM fragments to increase performance, but something along these lines should work for your use case.还有其他方法——使用for循环,或使用 DOM 片段来提高性能,但这些方法应该适用于您的用例。

The only missing part is how you loop over your data and add items to your list, so here's a quick example.唯一缺少的部分是如何遍历数据并将项目添加到列表中,所以这是一个简单的示例。

 // Cache the list element const ul = document.querySelector('ul'); // Your data will look something like this // where `data` is an object with a property // with an array const data = { cities: [ { name: 'London' }, { name: 'Paris' } ] }; // Once your data has returned, loop // over the array, and then add each new item // to the list for (const city of data.cities) { const item = document.createElement('li'); item.textContent = city.name; ul.appendChild(item); }
 <ul></ul>

If you wanted another approach that uses more "modern" methods:如果您想要另一种使用更“现代”方法的方法:

 // Cache the list element const ul = document.querySelector('ul'); // Your data will look something like this // where `data` is an object with a property // with an array const data = { cities: [ { name: 'London' }, { name: 'Paris' } ] }; // Create an array of HTML strings by mapping // over the data const html = data.cities.map(city => { return `<li>${city.name}</li>`; }).join(''); // And then adding that joined string to the list ul.insertAdjacentHTML('beforeend', html);
 <ul></ul>

Addition information添加信息

You need to update an element that is in the dom.您需要更新 dom 中的元素。

var listApi = document.querySelector(".list-item")
var searchApi = document.getElementById("search-api")
document.querySelector("#enter").addEventListener("click", e => {
    e.preventDefault();
    var inputValue = searchApi.value; 
    fetch('https://wft-geo-db.p.rapidapi.com/v1/geo/cities/'     +inputValue, options)
    .then(response => response.json())
    .then(response => console.log(response))
    .then((data) => {
        listApi.innerText = data;
    })
    .catch(err => console.error(err));

});

暂无
暂无

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

相关问题 构建Web应用程序:来自AngularJS文件的数据不会显示在HTML文档中 - Building a webapplication: Data from my AngularJS file won't display in my HTML document 我是编码新手。 我想在按下按钮后在我的 html 页面上的文本框中显示来自我的 javascript 文件的 java 代码结果 - I am new to coding. I would like to display my java code result from my javascript file in a text box on my html page after pressing a button 如何在我的 html 代码中获取 API 和显示数据? - How to fetch API and Display data in my html code? 我的API Weather应用程序的AJAX代码在做什么? 它不会从站点中提取数据 - What am I doing wrong in my AJAX code with my API weather app? It won't pull data from the site 如何从此api解析数据并将其显示在我的html中? - How to parse data from this api and display it in my html? 为什么我的 api 中的数据不会在我的 Vue 模板中呈现? - Why won't the data from my api render in my Vue template? 我的教授提出了HTML编码要求,但我没有关注 - HTML coding request from my professor and I don't follow 该图表未显示我使用 Axios 调用 API 的数据 - The chart doesn't display the data from my call to the API with Axios 为什么我的文本在 html 中的显示与 javascript 不同? - Why won't my text display the same in html as javascript? 为什么我的api json数据无法从循环读取我的属性并将html数据附加到dom? - Why my api json data can't read my properties from the loop and append the html data to the dom?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM