问题
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");
}
}
Here is the cgi program
#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:
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!
来源:https://stackoverflow.com/questions/7861447/ajax-readystate-always-equals-one