Beginner Question: Using Open Method Does Not Load My Text File
Solution 1:
In myFunction
the xmlhttp
variable is not in the scope of the function. This should be causing a JavaScript error, which you can view in Chrome by going to Menu > Tools > JavaScript console. One way to fix this would be to pass the xmlhttp
object as a parameter.
functionloadXMLDoc(url , cfunc) {
//some code...
xmlhttp.onreadystatechange=function() {
//pass xmlhttp as a parameter to this function and preserve the context//see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call
cfunc.call(this, xmlhttp);
}
//some more code...
}
functionmyFunction() {
loadXMLDoc("ajax_info.txt", function(xmlhttp) {
//xmlhttp is now in scope because we passed it as a parameter
});
}
Update
I created a working example at http://jsfiddle.net/6rPgE/
As for your question about the modifications I suggested...
The second parameter to the loadXMLDoc
method (cfunc
) is a function. In this case, an anonymous function is created inside myFunction
which will be passed as the cfunc
parameter to loadXMLDoc
. When the onreadystatechange
callback is invoked, the cfunc
function is called with xmlhttp
as the first parameter. This parameter is passed into the anonymous function defined inside myFunction
, and is responsible for actually doing something with the AJAX response. On an entirely different note, I highly recommend using a debugger (Chrome has one built-in) and the information provided by the browser's error console to assist you in debugging these issues in the future. Learning how to use a debugger will save you countless hours of banging your head against the wall.
Update 2
Just thought it would be nice to look at how this can be done using jQuery with quite a bit less code. AJAX is one area where it can be really nice to use a library that abstracts away the details.
Another example that uses jQuery at http://jsfiddle.net/j9QvE/1/
Update 3
Note that in my code I replaced the path to ajax_info.txt with a path specifically used for testing AJAX functionality in jsFiddle (/echo/js/?js=Success!). This was necessary because ajax_info.txt does not exist on the jsFiddle servers, so requesting it would have resulted in a 404 error. Don't forget to change the path to point to an appropriate resource on your own domain.
Post a Comment for "Beginner Question: Using Open Method Does Not Load My Text File"