虽然您不应该单独依赖客户端验证,并且绝对应该将所有数据视为PHP中的“脏”,但使用JavaScipt还有另一种方法可以阻止浏览器直接发布表单。不要设置表单的方法和操作,只需定义其onsubmit函数来构造XmlHttpResponse对象,将方法设置为POST并将数据设置为form.serialize(),并发送相应的POST请求。或者,如果PHP脚本将接受GET或REQUEST参数,您可以(在验证之后)构造URL查询并简单地设置window.location以使用适当的数据重定向到PHP页面。
编辑 - 这是我的插图 - 这使用Prototype的Form.serialize function。
Username:
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.');
}
}
}
有一些更复杂的方法来创建和处理XMLHttpRequest对象。我可能稍后会发布一些更新的指针。