Ajax readyState总是等于1

时间:2011-10-22 17:45:34

标签: javascript ajax cgi

您好我正在使用提交给C ++ cgi程序的ajax。我遇到的问题是readyState总是1.我不知道我做错了什么。

    var asyncRequest; // XMLHttpRequest object

    try
        {
            asyncRequest = new XMLHttpRequest();

            // Register event handler
            asyncRequest.onreadystatechange = StateChange; 

            // Prepare to post data to URL asynchronously
            asyncRequest.open("POST", "save_vote.cgi", true); 

            //Data to be sent to cgi program
            postData="star=1&movie=test";


            // Set the appropriate HTTP request headers
            asyncRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            asyncRequest.setRequestHeader("Content-length", postData.length);

            // Make request
            asyncRequest.send(postData);

         }
         catch (exception)
         {
            alert("Request failed: " + exception.message);
         }

}
function StateChange()
{

    // Make sure request has completed with 200 OK status

    //alert(asyncRequest.status)
    if (asyncRequest.readyState == 4 && asyncRequest.status == 200)
    {
        alert("Hello");
    }

}

这是cgi程序

#include "cgi.h"
#include <fstream>
    int main()
{
    cout << "Content-type: text/html\n\n";

    ParseInputParameters();

    ofstream fout;

    if (fout.fail())
    {
        cout << "CGI Error - Couldn't open file for appending for appending.";
        return 0;
    }


    //message to be sent back in the response text
        cout << "OK";

    fout.close();

    return 0;
}

1 个答案:

答案 0 :(得分:1)

将SateChange函数移动到正在进行XHR的函数体。修改完成后,asyncRequest内的StateChange将等于相关的asyncRequest对象。

function ajaxUpdate(){
    ....
    var asyncRequest; // XMLHttpRequest object
    try {
        asyncRequest = new XMLHttpRequest();
        ....
        asyncRequest.send(postData);
     }
     catch (exception){
        alert("Request failed: " + exception.message);
     }

    //} <---Removed curly bracket
    function StateChange(){

        // Make sure request has completed with 200 OK status

        //alert(asyncRequest.status)
        if (asyncRequest.readyState == 4 && asyncRequest.status == 200){
            alert("Hello");
        }
    }

} //<--Added curly bracket!