onreadystatechange in AJAX not working

2019-03-06 05:07发布

问题:

I have a problem with the onreadystatechange when i make ajax request, it used to call the function but now it does not call the processRequest.

I am not sure if I edited something or what..Can sombody help..

function createAjaxObject(url, callback) 
{
    /// @par Implementation 
    var req = init();
  req.onreadystatechange = processRequest;

    /// @brief  Creates a ajax object based on the runnunf browser    
    function init() 
    {
        if (window.XMLHttpRequest)
            return new XMLHttpRequest();
        else if (window.ActiveXObject) 
            return new ActiveXObject("Microsoft.XMLHTTP");
    }

    /// @brief Checks if request is complete and HTTP call is successful
    function processRequest () 
    {   

        /// readyState of 4 signifies request is complete

        if (req.readyState == 4){

            /// status of 200 signifies sucessful HTTP call
            if (req.status == 200){
                if (callback) 
                callback(req.responseXML);
            }
        }
    }

     this.doPost = function(param) {

             if (req.readyState == 4) {

        /// 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);

        }
    }
}

thanks,

回答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.