Page is a not externally linkable
- Code, Content, and Presentation
-- JavaScript and AJAX
---- A page to display nothing in browser window


Fotiman - 3:26 pm on Nov 23, 2011 (gmt 0)


nocache = '&nocache='+math.randon()*1000000
math should be Math (case matters)
random is spelled wrong.
It's good form to use 'var' to declare the variable, and also good to end with a semi-colon.

You're creating a lot of global variables (as a result of not using var). In general that should be avoided. In this particular case, your entire script is running in a global context, so you might consider cleaning it up some to reduce the number of globals you have.

The main problem I notice is that you're doing this:

request = new ajaxRequest();

But ajaxRequest is not a constructor method. It's just a regular old function that returns an object. So remove the "new" from that line.

In addition, the method you're using for getting the XMLHttpRequest object is a bit outdated. Here's an alternative:


/**
* Gets an XMLHttpRequest. For Internet Explorer 6, attempts to use MXSML 3.0.
* @return {XMLHttpRequest or equivalent ActiveXObject}
*/
function getXHR() {
return window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('MSXML2.XMLHTTP.3.0');
}


Then your code could be modified as follows:


var nocache = '&nocache=' + Math.random() * 1000000,
url = 'rss.news.yahoo.com/rss/topstories',
request = getXHR();

/**
* Gets an XMLHttpRequest. For Internet Explorer 6, attempts to use MXSML 3.0.
* @return {XMLHttpRequest or equivalent ActiveXObject}
*/
function getXHR() {
return window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('MSXML2.XMLHTTP.3.0');
}

request.open('GET', 'xmlget.php?url=' + url + nocache, true);
request.onreadystatechange = function () {
var j,
out = '',
titles;
if (this.readyState == 4) {
if (this.status == 200) {
if (this.responseXML != null) {
titles = this.responseXML.getElementsByTagName('title');
for(j = 0; j < titles.length; ++j) {
out += titles[j].childNodes[0].nodeValue + '<br />';
}
document.getElementById('info').innerHTML = out;
}
else {
alert('Ajax error: No data received');
}
}
else {
alert('Ajax error :'+ this.statusText);
}
}
}
request.send(null)


Note, I also moved your 'out' variable to have function scope instead of global scope (so that any additional requests don't append to a global variable which may contain previous request data).

Lastly, you may need to encodeURIComponent your url and nocache variables (or some of the contents within).


Thread source:: http://www.webmasterworld.com/javascript/4390273.htm
Brought to you by WebmasterWorld: http://www.webmasterworld.com