Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

接入一言语句接口 #52

Open
seeu100 opened this issue Apr 20, 2024 · 0 comments
Open

接入一言语句接口 #52

seeu100 opened this issue Apr 20, 2024 · 0 comments
Labels
记录 记录生活点滴 资源 好用的资源

Comments

@seeu100
Copy link
Owner

seeu100 commented Apr 20, 2024

在官方示例的基础上增加了来源,效果参考 https://blog.00002000.xyz/ 底部。

<!-- 这段代码的功能是从指定API获取一条随机的句子(Hitokoto)并将它展示在HTML页面上 -->

<span id="hitokoto_text">:D</span> —— <span id="hitokoto_from_who">:D</span><span id="hitokoto_from">:D</span><script>
  // 使用fetch API发起一个GET请求到'https://v1.hitokoto.cn'这个API地址
  fetch('https://v1.hitokoto.cn')
    // 当请求成功返回响应后,转化为JSON格式的数据
    .then(response => response.json())
    // 对JSON数据进一步处理
    .then(data => {
      // 获取页面中id为'hitokoto_text'的元素,并将其文本内容设置为API返回的hitokoto字段值
      const hitokoto_text = document.querySelector('#hitokoto_text');
      hitokoto_text.innerText = data.hitokoto;

      // 获取页面中id为'hitokoto_from'的元素,并将其文本内容设置为API返回的from字段值
      const hitokoto_from = document.querySelector('#hitokoto_from');
      hitokoto_from.innerText = data.from;

      // 获取页面中id为'hitokoto_from_who'的元素,并将其文本内容设置为API返回的from_who字段值
      const hitokoto_from_who = document.querySelector('#hitokoto_from_who');
      hitokoto_from_who.innerText = data.from_who;
    })
    // 如果在上述过程中出现任何错误,则在控制台输出错误信息
    .catch(error => console.error(error));
</script>

注释说明:这段JavaScript代码会动态加载来自https://v1.hitokoto.cn API接口的一条日文名言(Hitokoto)及相关的作者和出处信息,并将它们分别填充到HTML文档中对应ID的<span>标签内,实现页面内容的动态更新。

使用示例 | 一言开发者中心
hitokoto-osc/sentences-bundle: 一言开源社区官方提供的语句库,系 hitokoto.cn 数据库打包集合。语句接口默认使用此库。

@seeu100 seeu100 added 记录 记录生活点滴 资源 好用的资源 labels Apr 20, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
记录 记录生活点滴 资源 好用的资源
Projects
None yet
Development

No branches or pull requests

1 participant