我正在学习如何使用JavaScript从ASMX服务使用XMLHttpRequest类调用web方法。我已经成功地写:javascript,如何从XML获取值
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',并且因为那个特殊原因我需要这个。然而,我有一些问题...如果我的'xmlStr'来自'(..)。responseXML',那么为什么我应该创建一个字符串,然后再将它转换为XML并最终使用'getElement ...'?为什么我无法使用原始XML?它是只读还是其他? –
看来你可能不得不将内容类型头设置为text/xml:https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseXML – Greg
它说'如果服务器不' t指定Content-Type标头为text/xml或application/xml,则可以使用overrideMimeType()强制XMLHttpRequest将其解析为XML。# 问题是服务器将Content-Type指定为“text/xml” ,所以这有点奇怪。 –