[英]Why doesn't my AJAX script work?
我正在尝试获取以下代码来调用PHP文件,并显示返回的数据。 在Firefox中,警报显示为空白,而在IE中,警报有时显示,但几乎不显示任何内容。 PHP脚本是一个简单的echo "hello";
。
function make_request()
{
try
{
// Firefox, Opera 8.0+, Safari
httpxml=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
httpxml=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
httpxml=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
}
function check_login(username, password)
{
var httpRequest;
make_request()
var parameters = 'username=' + username.value + '&password=' + password.value;
httpxml.onreadystatechange = stateck;
httpxml.open('POST', 'login.php', true);
httpxml.setRequestHeader('Content-Type', "application/x-www-form-urlencoded");
httpxml.setRequestHeader('Content-Length', parameters.length);
httpxml.send(parameters);
function stateck()
{
if(httpxml.readyState==4)
{
alert(httpxml.responseText);
}
}
}
<table class="form" id="form" cellpadding="10" >
<form id="signup_form" name="form" method="post" />
<tr>
<td>Username</td>
<td><input type="text" name="username" id="username" size="26" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password" id="password" size="26"/></td>
</tr>
<td>
<input type="submit" name="button" id="button" value="Submit" onClick="check_login(username, password);"/>
</td>
</form>
</table>
</div>
谢谢
一些注释,我无法在注释中添加注释(其中一些注释对XMLHttpRequest调用的成功没有影响;其他注释可能 -请修复所有问题):
什么都不会检查make_request()的返回值,所以return false;
否则 , return false;
是毫无意义的(只是...返回)。 为什么不将httpxml设置为局部变量而不是隐式全局变量,然后将其返回? 然后使用返回值向调用方指示函数是否成功...
从未使用check_login()中的局部变量httpRequest 。 也许您打算为其分配make_request()的返回值(并且...让make_request()实际上返回有用的东西吗?)
您实际上并没有使用URL编码username或password的值。 (将它们通过encodeURIComponent()
传递即可轻松完成此操作)
您不需要显式设置Content-Length
标头。 (如果您弄错了,这很容易导致请求失败)
还有最严重的脚本错误:您不会取消“提交”按钮的默认行为。 从check_login()返回false,并将事件处理程序更改为onclick="return check_login(username, password);
您已经使<form>
标记自动闭合( <form ... />
)。 并包含一个结束</form>
标记。 这不太可能是您想要的(跨浏览器可靠运行的可能性更小)
您的最后一个单元格( <td>
)是在任何行( <tr>
)之外定义的。
关闭从未打开过的<div>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.