Ajax readyState始终等于1 [英] Ajax readyState always equals one

查看:177
本文介绍了Ajax readyState始终等于1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在使用提交到C ++ cgi程序的ajax。我遇到的问题是readyState始终为1。我没有弄错我在做什么。

Hello I'm working with ajax that submits to a C++ cgi program. The problem that I am having is the readyState is always 1. I don't get what I am doing wrong.

    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;
}


推荐答案

将SateChange函数移至生成XHR的功能的主体。修改之后, StateChange 中的 asyncRequest 将等于相关的 asyncRequest

Move the SateChange function to the body of the function where the XHR is being made. After this modification, the asyncRequest inside StateChange will equal the relevant asyncRequest object.

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!

这篇关于Ajax readyState始终等于1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆