Ajax readState 始终等于 1
你好,我正在使用 ajax 提交到 C++ cgi 程序。我遇到的问题是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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将 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
insideStateChange
will equal the relevantasyncRequest
object.