gpt4 book ai didi

javascript,如何从 XML 获取值

转载 作者:行者123 更新时间:2023-11-28 15:16:16 25 4
gpt4 key购买 nike

我正在学习如何使用 JavaScript 使用 XMLHttpRequest 类从 ASMX 服务调用 Web 方法。我已经成功编写了以下内容:

function GetDataService() {
if (window.XMLHttpRequest) {
xmlHTTP = new window.XMLHttpRequest;
} else {
alert("Wrong!");
}

xmlHTTP.open("POST", "http://localhost:45250/ServiceJava.asmx", true);
xmlHTTP.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHTTP.setRequestHeader("SOAPAction", "http://localhost:45250/ServiceJava.asmx/GetTimeString");

strRequest = '<?xml version="1.0" encoding="utf-8"?>';
strRequest = strRequest + '<soap:Envelope '
+ 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" '
+ 'xmlns:xsd="http://www.w3.org/2001/XMLSchema" '
+ 'xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">';
strRequest = strRequest + '<soap:Body>';
strRequest = strRequest + '<GetTimeString xmlns="http://localhost:45250/ServiceJava.asmx" />';
strRequest = strRequest + '</soap:Body>';
strRequest = strRequest + '</soap:Envelope>';

//Different value for readystate
//0--Uninitialized
//1--Loading
//2--loaded(but data not recieved)
//3--Interactive--Some part of the data is recieved
//4--Completed(all data recieved)
xmlHTTP.onreadystatechange = function () {
if (xmlHTTP.readyState == 4 && xmlHTTP.status == 200) {
var x = xmlHTTP.responseXML;
document.getElementById("time").textContent = x;
}
}
xmlHTTP.send(strRequest);
}

但它会生成代码:

<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><GetTimeStringResponse xmlns="http://localhost:45250/ServiceJava.asmx"><GetTimeStringResult>14:31:28</GetTimeStringResult></GetTimeStringResponse></soap:Body></soap:Envelope>

现在我只想获取14:31:28。我怎样才能做到这一点?我试图找到答案,但 x 似乎没有像 getElementByTagName() 这样的方法或任何类似的方法。

谢谢!

最佳答案

不使用 jQuery 的解决方案

var xmlStr = '<?xml version="1.0" encoding="utf-8"?><soap:Envelope ...';    
var xml = new window.DOMParser().parseFromString(xmlStr, "text/xml");
var value = xml.getElementsByTagName("GetTimeStringResult")[0].innerHTML;

关于javascript,如何从 XML 获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33781702/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com