Javascript-如何检索html标记';从一个响应中得到的值
正在向服务器发送HTTP GET。从服务器返回有效负载响应后,我需要提取html标记的值。我不知道该怎么做 这是将HTTP GET发送到服务器的代码:Javascript-如何检索html标记';从一个响应中得到的值,javascript,html,Javascript,Html,正在向服务器发送HTTP GET。从服务器返回有效负载响应后,我需要提取html标记的值。我不知道该怎么做 这是将HTTP GET发送到服务器的代码: <html> <script> function TEST() { var data = null; var xhr = new XMLHttpRequest(); xhr.withCredentials = true; xhr.addEventListener("readystatech
<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>
功能测试()
{
var数据=null;
var xhr=new XMLHttpRequest();
xhr.withCredentials=true;
xhr.addEventListener(“readystatechange”,函数(){
if(this.readyState==4)
{console.log(this.responseText);}
});
xhr.open(“GET”https://webadmin.domain.local/authenticate.html");
发送(数据);
}
把老鼠传过来
服务器返回响应,我需要提取会话密钥的值:
<input type="hidden" name ="Session-Key" value ="05aa6221dc982adb"/>
我需要提取会话密钥的值,以便在服务器的下一个请求中使用它。在我的脚本中执行此操作的代码是什么?str是从api接收的html字符串响应
let str=''
让doc=newdomparser().parseFromString(str,“text/xml”);
让val=doc.firstElementChild.getAttribute('value');
console.log(val)
您只需设置
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);
}
}
// ...
那么,您是否绑定了:
document.getElementsByName('Session-Key')[0].getAttribute('value')
?