【问题标题】:Iterate over JSON data and append field text to div (ES6)遍历 JSON 数据并将字段文本附加到 div (ES6)
【发布时间】:2020-01-18 16:59:03
【问题描述】:

我正在使用获取:

  fetch('https://www.website.com/wp-json/acf/v3/options/options')
    .then(function(response) {
      return response.json();
    })
    .then(function(myJson) {
      console.log(JSON.stringify(myJson));
    });
});

如何使用 ES6 来获取我的数据字段,它是文本内容;并附加到<p id="paragraph"></p>

示例数据/JSON 响应:

..'1yr_short_copy":"<p>Our 1 Year Money Back Guarantee either leaves you'..

基本上是在寻找使用 fetch 和 ES6(非 jQuery)的最佳方法。

期望的输出:

<p id="paragraph">Our 1 Year Money Back Guarantee either leaves you....</p>

【问题讨论】:

  • 那么 JSON 中有什么?目前尚不清楚阅读该对象有什么困难。
  • 也许分享一个示例输出会有所帮助。正如 epascarello 所指出的,您要做什么并不完全清楚,因此,您要问什么并不完全清楚。您的“数据字段”是什么,&lt;p id="paragraph&gt;... 在哪里?是在响应中还是在页面上?

标签: javascript json ecmascript-6 fetch


【解决方案1】:

首先将您的 JSON 解析为 response.json 中的 object,然后使用 JSON.stringify(myJson) 将其转回 JSON,这使其无法使用。不要那样做。只需使用您解析的object 来更新&lt;p id="paragraph"&gt;textContent 值。

因为您的 1yr_short_copy 属性以数字开头,您只能使用 brackets 而不是 dot 表示法来选择它。避免用数字命名对象中键的第一个字符。

fetch('https://www.website.com/wp-json/acf/v3/options/options')
  .then(function(response) {
    return response.json();
  })
  .then(function(obj) {
    const paragraph = document.getElementById('id');
    if (paragraph !== null && obj.hasOwnProperty('1yr_short_copy') { // Check if element is found and your 1yr_short_copy key exists.
       paragraph.textContent = obj['1yr_short_copy']; // Brackets notation
    }
  });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 2017-07-28
    • 1970-01-01
    • 2018-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多