0
這是代碼。我對JavaScript非常陌生,每天都在學習更多。這段代碼來自一本教科書的例子。謝謝你的回覆。我想問的另一個問題是如何在無序列表中顯示返回的文本?這是否會包含在html事物中,還是可以在JavaScript文件中完成?如何在新窗口/選項卡中打開文本和xml文件?
window.addEventListener("load",initAll,false);
var xhr = false;
function initAll() {
\t document.getElementById("makeTextRequest").addEventListener("click",getNewFile,false);
\t document.getElementById("makeXMLRequest").addEventListener("click",getNewFile,false);
}
function getNewFile(evt) {
\t makeRequest(this.href);
\t evt.preventDefault();
}
function makeRequest(url) {
\t if (window.XMLHttpRequest) {
\t \t xhr = new XMLHttpRequest();
\t }
\t else {
\t \t if (window.ActiveXObject) {
\t \t \t try {
\t \t \t \t xhr = new ActiveXObject("Microsoft.XMLHTTP");
\t \t \t }
\t \t \t catch (e) {
\t \t \t }
\t \t }
\t }
\t if (xhr) {
\t \t xhr.addEventListener("readystatechange",showContents,false);
\t \t xhr.open("GET", url, true);
\t \t xhr.send(null);
\t }
\t else {
\t \t document.getElementById("updateArea").innerHTML = "Sorry, but I couldn't create an XMLHttpRequest";
\t }
}
function showContents() {
\t if (xhr.readyState == 4) {
\t \t if (xhr.status == 200) {
\t \t \t if (xhr.responseXML && xhr.responseXML.childNodes.length > 0) {
\t \t \t \t var outMsg = getText(xhr.responseXML.getElementsByTagName("choices")[0]);
\t \t \t }
\t \t \t else {
\t \t \t \t var outMsg = xhr.responseText;
\t \t \t }
\t \t }
\t \t else {
\t \t \t var outMsg = "There was a problem with the request " + xhr.status;
\t \t }
\t \t document.getElementById("updateArea").innerHTML = outMsg;
\t }
\t
\t function getText(inVal) {
\t \t if (inVal.textContent) {
\t \t \t return inVal.textContent;
\t \t }
\t \t return inVal.text;
\t }
}