首页 > 解决方案 > 在我使用 axios 做出反应的其余 Web 服务请求中,响应 json 包含 html div 元素。我怎样才能得到这个元素的值?

问题描述

[
   {
      "title":"Palmeiras - Coritiba",
      "embed":"<div style='width:100%;height:0px;position:relative;padding-bottom:calc(56.25% + 335px);' class='_scorebatEmbeddedPlayerW_'><iframe src='https://www.somestream.com/embed/g/934437/?s=2' frameborder='0' width='560' height='650' allowfullscreen allow='autoplay; fullscreen' style='width:100%;height:100%;position:absolute;left:0px;top:0px;overflow:hidden;' class='_scorebatEmbeddedPlayer_'></iframe></div>",
      "url":"https://www.some.com/coritiba-vs-palmeiras-live-stream/",
      "thumbnail":"https://www.somestream.com/og/m/og934437.jpeg",
      "date":"2020-10-14T21:00:00+0000",
      "side1":{
         "name":"Palmeiras",
         "url":"https://www.some.com/live-stream/palmeiras/"
      },
      "side2":{
         "name":"Coritiba",
         "url":"https://www.some.com/live-stream/coritiba/"
      }
   }
]

我想从此响应中获取标题、缩略图和视频、日期字段,但无法获取视频,因为它位于 div 元素中。

标签: reactjs

解决方案


您需要使用DOMParser将 HTML 字符串读入 JavaScript 文档。您可以在其上使用 DOM 方法,例如 querySelector 和 getElementById。

这是一个从 HTML 嵌入字符串返回视频 src 的函数。

const getEmbedSrc = (embed) => {
  const parser = new DOMParser();
  const doc = parser.parseFromString(embed, "text/html");
  return doc.getElementsByTagName('iframe')[0].src;
}

const embed = "<div style='width:100%;height:0px;position:relative;padding-bottom:calc(56.25% + 335px);' class='_scorebatEmbeddedPlayerW_'><iframe src='https://www.somestream.com/embed/g/934437/?s=2' frameborder='0' width='560' height='650' allowfullscreen allow='autoplay; fullscreen' style='width:100%;height:100%;position:absolute;left:0px;top:0px;overflow:hidden;' class='_scorebatEmbeddedPlayer_'></iframe></div>";

console.log(getEmbedSrc(embed));

或者,您可以使用正则表达式查找匹配项。


推荐阅读