【问题标题】:Accessing Vars In All Script Tags In HTML Source Fetched Via xhr Request访问通过 xhr 请求获取的 HTML 源中所有脚本标记中的变量
【发布时间】:2019-05-19 01:00:46
【问题描述】:

如何从通过 xhr 请求获取的页面的 HTML 源代码中的脚本标签访问变量值。

获取页面的 HTML...

<html>
   <body>
   <div id="somecontent"></div>
      <script>
        var foo="30";
      </script>

      <script>
        var bar="60";
      </script>

   </body>
</html>

并通过 xhr 请求获取...

var xhr = new XMLHttpRequest();
xhr.open("GET","http://www.example.com/testpage.html");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
    var html = xhr.responseText;

    // try to access var 
    var result =html.foo+html.bar;

    console.log(result);

    } 

    }

   xhr.send();

任何想法将不胜感激!

【问题讨论】:

  • 你不能获取 JSON 而不是 HTML 吗?
  • 不,它必须是完整的 html 页面,然后从脚本标签中提取特定的 vars/json 对象...
  • 我认为@Armel 的建议可能是在这种情况下你能做的最好的。

标签: javascript html json ajax xmlhttprequest


【解决方案1】:

你可以试试这样的:

var xhr = new XMLHttpRequest();
xhr.open("GET","http://www.example.com/testpage.html");
xhr.onreadystatechange = function() {
  if (xhr.readyState == 4) {
    var html = xhr.responseText;
    var parser = new DOMParser();
    var dom = parser.parseFromString(html, 'text/html');
    var scripts = dom.querySelectorAll('script');

    for (let script of scripts) {
      eval(script.innerText);
    }

    console.log('foo', foo);
    console.log('bar', bar);
  }
}
xhr.send();

【讨论】:

    猜你喜欢
    • 2018-08-31
    • 2019-05-08
    • 1970-01-01
    • 2020-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-08
    相关资源
    最近更新 更多