【问题标题】:how to evaluate json response from meme api in html/javascript?如何评估来自 html/javascript 中 meme api 的 json 响应?
【发布时间】:2022-01-31 00:29:15
【问题描述】:

我想在我的网站中实现这个 API,这样我就可以从 reddit 中获取随机模因。

API 由 D3vd 在 github (https://www.github.com/D3vd/Meme_API) 上制作

我从https://meme-api.herokuapp.com/gimme/memes(api)得到的响应是这样的:

{
    "postLink": "https://redd.it/sg8j7b",
    "subreddit": "memes",
    "title": "No you respect the nature now!",
    "url": "https://i.redd.it/nk9eiy1nnte81.jpg",
    "nsfw": false,
    "spoiler": false,
    "author": "Abdul_Sbeei",
    "ups": 423,
    "preview": ["https://preview.redd.it/nk9eiy1nnte81.jpg?width=108\u0026crop=smart\u0026auto=webp\u0026s=253fc41547e5acc1ee3efcc0a4644e8d52d67181", "https://preview.redd.it/nk9eiy1nnte81.jpg?width=216\u0026crop=smart\u0026auto=webp\u0026s=6050660429dd3a4ae6699a0f42294c04fc1fae02", "https://preview.redd.it/nk9eiy1nnte81.jpg?width=320\u0026crop=smart\u0026auto=webp\u0026s=07ff549bbd76d2f25f509cece0149e7939427edd", "https://preview.redd.it/nk9eiy1nnte81.jpg?width=640\u0026crop=smart\u0026auto=webp\u0026s=baa9e058ba9722515aefa9ab28bb95235d0e151b"]
}

如何使用 javascript 仅获取图片链接(“url”),以便将其显示在我的网站上?

提前谢谢

【问题讨论】:

  • yourResponseObject.url...
  • 在 Javascript 中,使用 obj.key 访问键 例如 let obj = {a: 'test'};控制台日志(obj.a); // 这将打印 test 如果你的 API 响应,你可以说 obj.url
  • 请显示您用于获取 API 数据的代码
  • 我通过访问 url 得到了输出

标签: javascript html json


【解决方案1】:

使用 fetch 的一些非常基本的 ajax 代码就足够了:

fetch('https://meme-api.herokuapp.com/gimme/memes')
  .then(r=>r.json())
  .then(json=>{
    console.log( json.url )
  })

【讨论】:

  • 这是教给你的最好方法,仅限于对象
  • 这些图片加载后是否可以保存在服务器上?
  • 是的,这是可能的。为此,最初使用fetch 来获取 json 数据将是复杂且低效的。假设您为网站使用的任何服务器都具有 PHP 或类似语言,您可能希望使用一种技术,其中 json 由服务器下载(cURL、file_get_contents 或其他),由服务器处理(在此阶段保存文件)和向浏览器发送内容
猜你喜欢
  • 2014-07-06
  • 1970-01-01
  • 2016-08-06
  • 2011-01-14
  • 2018-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-09
相关资源
最近更新 更多