Onreadystatechange In Ajax Not Working
Solution 1:
This line:
if (req.readyState == 4) {
...(and the corresponding }
) shouldn't be in the function you're assigning to this.doPost
. E.g.:
this.doPost = function(param) {
/// make a HTTP GET request to the URL asynchronously
req.open("POST",url, true);
req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
req.setRequestHeader("Content-length",param.length);
req.setRequestHeader("Connection", "close");
req.send(param);
};
I'm assuming the way you use that is:
var obj = new createAjaxObject(url, callback);
obj.doPost();
...because the code quoted never actually calls the function that does the post, but rather just assigns it to a property on this
. The usual place you assign properties to this
is within a constructor function, hence my using new
above.
(BTW: The overwhelming convention in JavaScript code is to use initial caps on functions that are used as constructors, e.g. CreateAjaxObject
[or better yet, just AjaxObject
] rather than createAjaxObject
.)
There are a bunch of other changes I'd make to that code, but I think that's the minimum.
Side note: I'd recommend using a JavaScript library like jQuery, Prototype, YUI, Closure, or any of several others. They smooth over a lot of browser differences and provide a huge amount of well-tested utility functionality, letting you focus on what you actually need to do.
Post a Comment for "Onreadystatechange In Ajax Not Working"