表单不会在提交时调用JS函数

时间:2013-10-20 14:53:58

标签: javascript jquery ajax

我忘记了传递表单,在提交时没有调用我的javascript ajax,这是我的代码

<form onsubmit="SendMail(this.email.value);">
                <input type="email" name="email" placeholder="E-Mail" required>
                <input type="submit" id="black_button" value="Request Password Renewal Code">
            </form>

这是我的JS脚本

<script>
        function SendMail(email)
        {
            if (window.XMLHttpRequest)
            {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp=new XMLHttpRequest();
            }
            else
            {// code for IE6, IE5
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange=function()
            {
                if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {
                    var response = xmlhttp.responseText;
                    if(response=='redirect')
                    {
                        document.location.href="forgotpassword.php?success=1"; //If the response is redirect then redirect the user to another page
                    }
                    else
                    {
                        $("#FPErrorMSG").html(xmlhttp.responseText);
                        $("#FPErrorMSG").css("display","block"); // If not then show the error message
                    }
                }
            }
            xmlhttp.open("GET","system/forgotpassword/sendmail.php?email=" + email,true);
            xmlhttp.send();
        }
    </script>

它没有调用Javascript函数,例如当我输入我的电子邮件为abc@d.com时,它只会将我的URL更改为forgotpassword.php?email=abc@d.com。当我将输入字段名称从电子邮件更改为邮件时,它将我的URL更改为forgotpassword.php?mail=abc@d.com

1 个答案:

答案 0 :(得分:0)

您应该在javascript函数中返回false。否则,在调用javascript函数后,表单将以正常方式提交。

<form onsubmit="return SendMail(this.email.value);">

function SendMail(email) {
   ...
   return false;
}

<form onsubmit="SendMail(this.email.value); return false;">

您应该查看this问题。