[英]javascript, how to get a value from XML
我正在學習如何使用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;
您可以使用例如jQuery parseXML方法。
var response = "<?xml version="1.0" encodi...";
var xml= $($.parseXML(response));
var value = xml.find("GetTimeStringResult").text();
但是,如果您選擇使用jQuery而不是普通的javascript發送請求,則會在回調中獲得已經反序列化的響應。
我建議您不要手工編寫XMLHttpRequests。 而是使用jQuery.ajax():
$.ajax({
url: "http://localhost:45250/ServiceJava.asmx/GetTimeString",
type: "POST",
data: postData,
success: function(data, textStatus, jqXhr) {
var result = data.GetTimeStringResult;
}
});
“ postData”應該是一個JSON對象,您可以在其中將參數傳遞給端點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.