【问题标题】:Fetching JSON response and display in HTML elements获取 JSON 响应并在 HTML 元素中显示
【发布时间】:2021-05-07 22:44:40
【问题描述】:

我正在尝试获取 JSON 响应并将它们显示在我预设的 HTML 元素中。我正在使用graphql(由datocms提供)。

API 浏览器显示我的模型:

query MyQuery {
  allNews {
    id
    newsTitle
    newsExcerpt
    newsContent
    newsCategory
  }
}

返回:

{
  "data": {
    "allNews": [
      {
        "id": "21003677",
        "newsTitle": "The amazing news",
        "newsExcerpt": "The amazing news to waste your afternoon.",
        "newsContent": "\nThe amazing news is unlike other news to waste your afternoon. It indeed wastes your afternoon in a way unimaginable, never before achieved.\n\nThe News consist of fake news and Trumpian staple conspiracies. ",
        "newsCategory": "News"
      }
    ]
  }
}

获取:

const token = 'the_token_here';
fetch(
  'https://graphql.datocms.com/',
  {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      'Authorization': `Bearer ${token}`,
    },
    body: JSON.stringify({
      query: '{ allNews { newsTitle } }'
    }),
  }
)
.then(res => res.json())
.then((res) => {
  console.log(res.data)
})
.catch((error) => {
  console.log(error);
});

加载静态 HTML 页面时,我想在 HTML 预设元素中显示 JSON 响应:

<h4 class="news--title">$(newsTitle.name)</h4>
<div class="news--description">${newsContent.name}</div>

是否可以使用 vanilla javascript,以及如何使用?

另外,如果响应不止一个(例如,10 个响应)并且我有四个这样的元素组,那么四个 JSON 响应(基于四个最大的 ID 号)是否可以迭代到四个 HTML 元素,如何?

对不起,如果问题是愚蠢的或已在其他地方提出和回答。我开始学习 javascript,之前从未使用过 API 调用/JSON。

【问题讨论】:

    标签: javascript json graphql


    【解决方案1】:

    您正在寻找模板文字。你可以有这样的文字:

    var myText = `This is a trivially simple template literal`;
    

    或者这个:

    var myParam = "great";
    var myText2 = `I have a ${myParam} day!`;
    

    这将评估为“我今天过得很愉快!”。

    现在,如果你想创建一个模板,你可以这样做:

    function myTemplate(titleName, titleContent) {
        return `
            <h4 class="news--title">${titleName}</h4>
            <div class="news--description">${titleContent}</div>
        `;
    }
    

    假设你有很多这样的项目要生成,你可以这样做:

    var items = [
        {titleName: 'a', titleContent: 'b'},
        {titleName: 'c', titcleContent: 'd'},
        //...
    ];
    var myTemplates = [];
    for (let item of items) myTemplates.push(myTemplate[item.titleName, item.titleContent]);
    myContainer.innerHTML = myTemplates.join("");
    

    使用 vanilla JS 也可以通过请求获取 JSON,您有大量的资源可供阅读。示例:https://www.w3schools.com/js/js_ajax_intro.asp

    您甚至可以实现一些可以帮助您发送请求的东西,而不是处理 Javascript 的原生支持,例如:

    function sendRequest(type, url, callback, async, params) {
        if (async !== false) async = true;
        var xhttp = new XMLHttpRequest();
        console.log(callback);
        xhttp.onreadystatechange = callback;
        xhttp.open(type, url, async);
        xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhttp.send(params);
    }
    

    【讨论】:

      【解决方案2】:

      我不是很明白你的问题,但是如果你只是想设置元素的内容,试试这个:

      // other code here
      const exampleData = { title: "Hello", content: "This is the content" };
      document.querySelector(".news--title").innerHTML = exampleData.title;
      document.querySelector(".news--description").innerHTML = exampleData.content;
      <h4 class="news--title"></h4>
      <div class="news--description"></div>

      document.querySelector 是一个函数,它将返回通过 CSS 查询找到的第一个元素。

      如果您有多个“新闻”,您可以对它们进行迭代并对它们执行相同的操作。

      【讨论】:

      • 我应该怎么做才能将 res.json 中的 JSON 响应变成这个? --> const exampleData = { title: "Hello", content: "这是内容" };获取 JSON 响应的目的是让我可以自动将响应用于 HTML 元素。
      • 我还是不太明白,如果我没看错的话,把exampleData替换成你的数据所在的对象innerHTML。
      猜你喜欢
      • 2017-02-16
      • 1970-01-01
      • 2017-10-31
      • 1970-01-01
      • 2017-02-27
      • 2021-03-17
      • 1970-01-01
      • 2020-04-20
      • 2017-06-04
      相关资源
      最近更新 更多