儘管您不應該單獨依賴客戶端驗證,並且應該將所有數據都視爲「髒」,但使用JavaScipt可以防止瀏覽器直接發佈表單。只需定義其onsubmit函數來構造XmlHttpResponse對象,將方法設置爲POST並將數據設置爲form.serialize(),然後發送相應的POST請求,而不是設置表單的方法和動作。或者,如果PHP腳本將接受GET或REQUEST參數,則可以(在您驗證之後)構造URL查詢並簡單地將window.location設置爲使用適當的數據重定向到PHP頁面。
編輯 - 這是我的插圖 - 這使用原型的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對象。我稍後可能會發布一些更新。
爲什麼放棄對非JS用戶的支持,以便在JS活動時可以實現不同的功能?我不明白。 – 2009-10-30 13:55:56
我根本不會。我只是指出了一種完成問題的方法。我會建議堅持服務器端驗證,永遠不要依賴JS。 – defines 2009-10-30 14:16:59
@Dustin:你能說明一下嗎? – RKh 2009-10-30 15:25:27