Chris Carrara
Chris Carrara

Reputation: 1

How do I have the text and xml files open in a new window/tab?

Here is the code. I am fairly new to JavaScript and I'm learning more every day. This code is from an example from a textbook. Thank you for your responses. Another question I'd like to ask is how can I display the returned text in an unordered list? Would that be something to include in the html side of things or can it be done within the JavaScript file?

window.addEventListener("load",initAll,false);
var xhr = false;

function initAll() {
	document.getElementById("makeTextRequest").addEventListener("click",getNewFile,false);
	document.getElementById("makeXMLRequest").addEventListener("click",getNewFile,false);
}

function getNewFile(evt) {
	makeRequest(this.href);
	evt.preventDefault();
}

function makeRequest(url) {
	if (window.XMLHttpRequest) {
		xhr = new XMLHttpRequest();
	}
	else {
		if (window.ActiveXObject) {
			try {
				xhr = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e) {
			}
		}
	}

	if (xhr) {
		xhr.addEventListener("readystatechange",showContents,false);
		xhr.open("GET", url, true);
		xhr.send(null);
	}
	else {
		document.getElementById("updateArea").innerHTML = "Sorry, but I couldn't create an XMLHttpRequest";
	}
}

function showContents() {
	if (xhr.readyState == 4) {
		if (xhr.status == 200) {
			if (xhr.responseXML && xhr.responseXML.childNodes.length > 0) {
				var outMsg = getText(xhr.responseXML.getElementsByTagName("choices")[0]);
			}
			else {
				var outMsg = xhr.responseText;
			}
		}
		else {
			var outMsg = "There was a problem with the request " + xhr.status;
		}
		document.getElementById("updateArea").innerHTML = outMsg;
	}
	
	function getText(inVal) {
		if (inVal.textContent) {
			return inVal.textContent;
		}
		return inVal.text;
	}
}

Upvotes: 0

Views: 460

Answers (1)

SirPython
SirPython

Reputation: 647

By the looks of it, you are making an AJAX request and are receiving XML.

In this case, I would:

  1. Open up a new page with window.open()(returns a new Window object)
  2. And then change the document.body.innerHTML of that new page to the XML you have

If you had a webpage that held the XML(maybe the server you are requesting to has one), you can just do:

window.open("page.xml");

Upvotes: 1

Related Questions