0

我有一个使用 ajax 发布表单值的表单,并且似乎它没有读取required表单输入上的属性。谁能告诉我有什么问题?

代码:

<script>
    $(function () {
        $("#send-email").click(function () {
            var subject = $("#subject").val();
            var name = $("#name").val();
            var email = $("#email").val();
            var phone = $("#phone").val();
            var message = $("#message").val();
            var nationality = document.getElementById("nationality");
            var selNationality = nationality.options[nationality.selectedIndex].text;
            //
            $.post("mail.php", {"subject": subject, "name": name, "email": email, "phone": phone, "nationality": selNationality, "message": message, }, function () {
                console.log(subject);
                console.log(name);
                console.log(email);
                console.log(phone);
                console.log(selNationality);
                console.log(message);
                alert("Thanks for contacting us, we will be back to you as soon as possible!");
            });

        });
    });
</script>
<form action="mail.php" method="POST">
    <div class="form-row">
        <p>Subject</p>
        <input type="text" id="subject" name="subject" required>            
        </select>
    </div>  
    <div class="form-row">
        <p>Name</p>
        <input type="text" id="name" name="name" required>          
    </div>
    <div class="form-row">
        <p>Nationality</p>
        <select name="nationality" id="nationality" required>
            <option value="">Select Nationality</option>            
        </select>           
    </div>
    <div class="form-row">
        <p>Contact number</p>   
        <input type="text" id="phone" name="phone">     
    </div>
    <div class="form-row">
        <p>Email</p>
        <input type="text" id="email" name="email" required>            
    </div>  
    <div class="form-row">
        <p>Message</p>  
        <textarea style="width:590px;height:100px;" id="message" name="message" cols="80" rows="12" required></textarea>
    </div>
    <div class="form-row">

    </div>
    <div class="form-row">
        <input type="submit" onclick="return false;" id="send-email" value="SEND" name="send"/>     
    </div>
</form> 
4

1 回答 1

0

你这里有几件事错了。解决方案取决于您的需求。

1)如果您不需要对 的异步调用mail.php,只需删除 javascript 的东西。当您这样做时:<form action="mail.php" method="POST">您的所有表单输入都将使用 POST 发送到所选操作,因此您不需要使用 javascript。

2)如果你确实需要异步加载,mail.php你需要做几件事才能工作:

  • 从表单标签中删除所有属性:<form>
  • onclick="return false;"从提交按钮标签中删除
  • 检查自己的数据完成情况,例如:

    var complete = true;
    if(subject==""||name==""||email=="") {
       complete = false;
    }  
    if(complete) {
       //send post to mail.php
    } else {
       alert("You need to fill in all the fields");
    }
    

请记住,并非所有资源管理器都支持此功能:http ://www.w3schools.com/tags/att_input_required.asp

于 2013-10-17T14:24:48.103 回答