簡體   English   中英

僅在onSubmit js驗證為true時才在表單操作中調用php函數

[英]Calling php function in form action only if onSubmit js validation is true

不知道從這里去哪里。 可能犯了很多錯誤,但是可以解決。

我希望我的表單首先通過onSubmit調用js驗證,並且僅在驗證變為true時才通過操作執行php函數...如果這樣做有意義,甚至可能嗎?

我的表格:

<form method="post" name="editForm" action="edit_account.php" onsubmit="return checkForm();">
    <label>Change email:</label>
    <input type="text" name="changeMail" value="<?php echo htmlentities ($_SESSION['sess_email'], ENT_QUOTES, 'UTF-8'); ?>">
    <label>Change password:</label>
    <input type="text" name="changePass">
    <input type="submit" name="submit" value="Save changes">
</form>

Javascipt驗證:

<script type="text/javascript">
function checkForm() {

    var x = document.forms["editForm"]["changeMail"].value;
    var atpos = x.indexOf("@");
    var dotpos = x.lastIndexOf(".");

    if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
        alert("Not a valid E-mail address");
        this.changeMail.focus();
        return false;
    }
}
</script>

PHP功能:

function edit_account_update(){
     <h1>Hello</h1>
}

以及從表單動作執行PHP功能的if語句:我知道當前使用$ _POST ['submit'],因此if語句始終在提交后激活,但是我不希望這樣。

if(isset($_POST['submit'])) {
    edit_account_update();
}

您應該在此行看到錯誤-觀察開發人員控制台(F12):

this.changeMail.focus();

因為您的checkForm()函數在沒有任何上下文的情況下被調用,所以this將引用window對象而不是表單。

您可以使用Function.prototype.call()將上下文綁定在onsubmit屬性中:

onsubmit="return checkForm.call(this);"

或者(最好)使用不引人注目的JavaScript。

window.onload = function(){
    document.forms["editForm"].onsubmit = checkForm;
};

通過以上操作, checkForm將自動應用this上下文。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM