简体   繁体   English

如何创建一个自动的html输入文本字段,以显示从API提取的值?

[英]How to create an automated html input text field that will display values being fetched from an API?

I want to build an input text field which when clicked will show a list of values being fetched via the contentful API. 我想构建一个输入文本字段,单击该字段将显示通过内容API获取的值的列表。 The code doesnt seem to work when it reached the forEach loop. 到达forEach循环时,该代码似乎不起作用。 It works fine till the initArray. 直到initArray都可以正常工作。 The forEach loop doesnt seem to work. forEach循环似乎不起作用。 I see all my data in the console.log of the initArray. 我在initArray的console.log中看到了所有数据。

Am I missing something? 我想念什么吗?

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"/> <title> URL Builder </title> <link rel="stylesheet" href="https://contentful.github.io/ui-extensions-sdk/cf-extension.css"> <script src="https://unpkg.com/contentful-ui-extensions-sdk@3"></script> </head> <body> <form id="urlSearchContainer"> <div class="cf-form-field"> <input list="urlDataList" type="search" placeholder="Type your url here..." id="urlBuilder" class="cf-form-input"> <datalist id="urlDataList"> </datalist> </div> </form> <script> "use strict" window.contentfulExtension.init(function(api) { api.window.startAutoResizer(); // Set variables var urlDataList = document.getElementById("urlDataList"); var urlInput = document.getElementById("urlBuilder"); function getUrlData(){ //api.space.getEntries({'content_type[ne]': 'page-MBH'}) var urlDataArray = []; api.space.getEntries() .then(function (entries) { entries.items.forEach(function (entry) { if(entry.fields.url){ var urlData = entry.fields.url.en urlDataArray.push(urlData); //console.log('urldata', urlDataArray); } }) }) return urlDataArray; }; function createUrlDropdown(){ // Init data obj var data = getUrlData(); var initArray = typeof data === 'object' && data instanceof Array && data.length > -1 ? data : []; console.log('ARRAY:: ', initArray); //Create and append url data list initArray.forEach(function(item) { console.log('item:: ', item); //Create a new <option> element. var option = document.createElement('option'); console.log('option', option); option.value = item; console.log('value', option); // Add the <option> element to the <datalist>. urlDataList.appendChild(option); }); for(i = 0; i < initArray.length; i++) { console.log('obj'); var option = document.createElement("option"); option.value = initArray[i]; urlDataList.appendChild(option); } } document.getElementById("urlBuilder").addEventListener("click", function(){ createUrlDropdown(); }); }); </script> </body> </html> 

Any help is appreciated!! 任何帮助表示赞赏!

👋🏻 👋🏻

The problem is in the getUrlData function. 问题出在getUrlData函数中。 api.space.getEntries returns a promise which you correctly use with then . api.space.getEntries返回您可以正确使用then的promise。 The thing with promises is though that they're asynchronous (like so many things in javascript). 尽管承诺是异步的(就像javascript中的很多东西一样),但是它们的承诺是一样的。

Meaning you initialize urlDataArray and make the call to contentful. 意思是您初始化urlDataArray并进行urlDataArray的调用。 And you fill this array when the call comes back. 当调用返回时,您将填充此数组。 The thing is though getUrlData already returned an empty array. 问题是尽管getUrlData已经返回了一个空数组。

    function getUrlData(){
      var urlDataArray = [];
      api.space.getEntries()
      .then(function (entries) {
        // this part is executed async
        entries.items.forEach(function (entry) {
          if(entry.fields.url){
            var urlData = entry.fields.url.en
            urlDataArray.push(urlData);
          }
        })
    })
      return urlDataArray;
    };

The best way to approach this IMO to change getUrlData to also return a promise. 解决此IMO的最佳方法是更改getUrlData并返回诺言。

function getUrlData() {
  // return this promise
  return api.space.getEntries()
    .then(function(entries) {
      // there is no need for another array
      // you can use map to grab the data you need
      return entries.items.map(function(item) {
        // map all the entries to the url strings
        return item.fields.url.en;
      })
    })
}

getUrlData()
  // only execute this when the data is there
  .then(function(urls) { console.log(urls); })

You code runs in a UI-extension but I also quickly changed your code in a codepen . 您的代码在UI扩展中运行,但我也很快在codepen中更改了您的代码。 It uses the Contentful CDA but the principles stays the same. 它使用内容CDA,但原理保持不变。

Hope that helps. 希望能有所帮助。 :) :)

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

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