在表单中,如果验证通过,我将调用PHP文件。我的表头标题如下所示:
<form method="POST" action="inst.php" style="margin:0px;"name="form1" onSubmit="return CheckUsername(document.getElementById('username').value);">
</form>
问题是即使验证失败,它也会显示一个空白页面,试图打开PHP文件,当它必须保留在同一页面上时。 PHP文件包含访问数据库以检查用户是否存在的代码。
有没有办法在不刷新页面的情况下检查数据库的值?
答案 0 :(得分:2)
JavaScript函数很可能有错误。然后不执行验证功能并发送表格(!)。检查Firefox的Javascript控制台是否有错误,即使页面已经重新加载,它们也会出现在那里。
但是,您应该永远不要依赖客户端验证。我强烈建议您同时检查PHP脚本。
答案 1 :(得分:1)
虽然您不应该单独依赖客户端验证,并且绝对应该将所有数据视为PHP中的“脏”,但使用JavaScipt还有另一种方法可以阻止浏览器直接发布表单。不要设置表单的方法和操作,只需定义其onsubmit函数来构造XmlHttpResponse对象,将方法设置为POST并将数据设置为form.serialize(),并发送相应的POST请求。或者,如果PHP脚本将接受GET或REQUEST参数,您可以(在验证之后)构造URL查询并简单地设置window.location以使用适当的数据重定向到PHP页面。
编辑 - 这是我的插图 - 这使用Prototype的Form.serialize function。
<form id="my_form" onSubmit="return checkUsername();">
Username: <input type="text" name="username" id="username" />
</form>
<script type="text/javascript">
var xhr; // global XMLHttpRequest object
var formElem = $('my_form'); // our form element
function checkUsername() {
var formData = formElem.serialize();
sendPOSTRequest('http://mydomain.com/mypath/myscript.php', formData);
}
function sendPOSTRequest(toURL, sendData) {
xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!xhr) {
alert('Cannot create XHR');
return false;
}
xhr.onreadystatechange = handleResponse;
xhr.open('POST', toURL, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", sendData.length);
xhr.setRequestHeader("Connection", "close");
xhr.send(sendData);
}
function handleResponse() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var result = xhr.responseText;
// result is now whatever content was returned by the PHP script
// do whatever you want with the result here
// for example, you might have the PHP return 'true' or some such thing, and then
// change window.location, or perhaps if it returns 'false' you put up an alert('No!')
// use your imagination, go nuts
} else {
alert('The script returned an error.');
}
}
}
</script>
有一些更复杂的方法来创建和处理XMLHttpRequest对象。我可能稍后会发布一些更新的指针。
答案 2 :(得分:0)
一旦POST请求被发送,那么由浏览器决定它如何处理响应,但在我遇到的每个浏览器中,它都会在某些浏览器中显示请求的结果,因为它是一条消息,表示已收到回复响应(200,404等),空白页面或其他任何内容,所以我担心您必须重新构建页面并将其发送回客户端(表单元素中包含无效条目)作为回复。
这很痛苦,但这就是HTTP的工作方式。