我试图让下面的代码调用 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;
有点毫无意义(只是......返回)。为什么不将 httpxml 设为局部变量而不是隐式全局变量,然后返回该变量?然后使用返回值向调用者指示函数是否成功...
check_login() 中的局部变量 httpRequest 从未被使用过。也许您打算将 make_request() 的返回值分配给它(并且...make_request() 实际上返回了一些有用的东西?)
您实际上并未对用户名或密码的值进行URL编码。 (通过 encodeURIComponent()
轻松完成此操作)
您不需要设置 Content-Length
明确 header 。 (而且如果写错了,很容易导致请求失败)
最严重的脚本错误:您没有取消提交按钮的默认行为。从 check_login() 返回 false,并将事件处理程序更改为 onclick="return check_login(username, password);
标记
您已经创建了 <form>
标签自关闭( <form ... />
)。并包括结束语</form>
标签。这不太可能是您想要的(更不可能在跨浏览器上可靠地运行)
最后一个单元格 ( <td>
) 是在任何行 ( <tr>
) 之外定义的。
您关闭了<div>
从未被打开过。
关于javascript - 为什么我的 AJAX 脚本不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1735255/