Why is defining an AJAX process failing when the tests are successful?
I'm developing an AJAX-based risk-style game, and a collaborator (who has since left) wrote this code:
function init() {
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","risk.xml",true);
xmlhttp.send(null);
xmldoc=xmlhttp.responseXML;
[snip]
document.getElementById('player').value='red'
[snip]
redterrs=xmldoc.getElementsByTagName('redterrs')[0]
blueterrs=xmldoc.getElementsByTagName('blueterrs')[0]
purpleterrs=xmldoc.getElementsByTagName('purpleterrs')[0]
greenterrs=xmldoc.getElementsByTagName('greenterrs')[0]
When I try to execute this I get this error in WebKit: "Uncaught TypeError: Cannot call method 'getElementsByTagName' of null" on "redterrs=xmldoc.getElementsByTagName('redterrs')[0]", but when I do it in Firefox with Firebug it tells me xmldoc is not defined.
Edit: In case anyone wan开发者_如何学Goted to see more of this, project is hosted at http://code.google.com/p/risk-board-game.
You are getting the XML document asynchronously, but you are not using an event handler to find out when the XML document has been received. Since you probably should be doing this synchronously, and since it is much simpler, try this in place of line 3:
xmlhttp.open("GET","risk.xml",false);
if you are using a naked XmlHttpRequest object, you need to register a callback for onreadystatechange
. This will be fired as the XHR goes through its states.
What you are doing wrong is assigning xmldoc
to xmlhttp.responseXML
outside of the callback.
Take a look at this: http://ajaxpatterns.org/XMLHttpRequest_Call#Asynchronous_Calls
精彩评论