-1

将 HTTP GET 发送到服务器。从服务器返回有效负载响应后,我需要提取 html 标记的值。我不知道执行此操作的代码

这是向服务器发送 HTTP GET 的代码:

<html>
 <script>
  function TEST()
  {
   var data = null;
   var xhr = new XMLHttpRequest();
   xhr.withCredentials = true;
   xhr.addEventListener("readystatechange", function () {
   if (this.readyState === 4) 
   { console.log(this.responseText);}
       });
   xhr.open("GET", "https://webadmin.domain.local/authenticate.html");
   xhr.send(data);
  }
 </script>
 <b onmouseover = "TEST()">pass mouse here</b>
</html>

服务器返回响应,我需要提取 Session-Key 的值:

<input type="hidden" name ="Session-Key" value ="05aa6221dc982adb"/>

我需要提取 Session-Key 的值,这样我就可以将它用于对服务器的下一个请求。在我的脚本中执行此操作的代码是什么?

4

2 回答 2

0

您可以简单地设置

xhr.responseType = "document"

然后得到xhr.responseXML而不是xhr.responseText

xhr.responseXML将是HTMLDocument的实例,因此您将能够使用querySelector方法来获取您需要的数据。

// ...
if (xhr.responseXML) {
    const sessionKeyNode = xhr.responseXML.querySelector('[name="Session-Key"]');

    if (sessionKeyNode) {
        console.log(sessionKeyNode.value);
    }
}
// ...
于 2019-11-07T17:35:38.853 回答
0

str 是从 api 接收的作为 html 字符串的响应

  let str = '<input type="hidden" name ="Session-Key" value ="05aa6221dc982adb"/>'
     let doc = new DOMParser().parseFromString(str, "text/xml");
         let val = doc.firstElementChild.getAttribute('value');
         console.log(val)

于 2019-11-07T17:33:59.527 回答