【问题标题】:how to make a form submit without reloading the page [duplicate]如何在不重新加载页面的情况下提交表单[重复]
【发布时间】:2016-12-05 19:59:51
【问题描述】:

如何在不重新加载页面的情况下提交表单我知道我必须使用 ajax 但我该怎么做?

html 文件:

<form name='myform' method="post" action="send.php">
                <span class="close-btn" id="close">&#10006;</span>
                <p>Введите свои контактные данные</p>
                <p>Мы Вам перезвоним</p>
                <input type="text" name="name" placeholder="Имя" maxlength="30">
                <p class="Error" id="Error">Это поле обязательное для заполнения</p>
                <p class="ErrorTwo" id="ErrorTwo">Некорректный ввод</p>
                <input type="tel" name="phone" placeholder="Телефон" maxlength="13">
                <p class="Error" id="telError">Это поле обязательное для заполнения</p>
                <p class="ErrorTwo" id="telErrorTwo">Некорректный ввод</p>
                <input type="submit" value="Отправить заявку"  name="save" id="save" disabled>
                <p>Данные не передаються третьим лицам</p>
            </form>

php:

<?php 
$ToEmail = 'myemail@gmail.com'; 
$EmailSubject = 'форма обратной связи'; 
$mailheader = "From: ".$_POST["email"]."\r\n";
$MESSAGE_BODY = "Имя: ".$_POST["name"].""; 
$MESSAGE_BODY .= "Телефон: ".$_POST["phone"].""; 
mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader) or die ("Failure"); 
?>

js:

/--------------验证------------- ---------------------------/

   //validation name
    document.myform.name.onchange= function() {
        var name = document.myform.name.value;
        if (name === "") {
            document.myform.name.removeAttribute("class", "ready");
            document.myform.name.style.border = "1px solid #da3637";
            document.getElementById("Error").style.display = "block";
            document.getElementById("ErrorTwo").style.display = "none";
        } else {
                document.myform.name.style.border = "1px solid #509d12";
                document.getElementById("Error").style.display = "none";
                var pattern = new RegExp("^[a-z]+$", "i");
                var isValid = this.value.search(pattern) >= 0;
                if (!(isValid)) {
                    document.myform.name.style.border = "1px solid #da3637";
                    document.getElementById("ErrorTwo").style.display = "block";
                    document.myform.name.removeAttribute("class", "ready");
                } else {
                    document.getElementById("ErrorTwo").style.display = "none";
                    document.myform.name.style.border = "1px solid #509d12";
                    document.myform.name.setAttribute("class", "ready");
                }
        }
    };


    //validation phone
    document.myform.phone.onchange = function() {
        var name = document.myform.phone.value;
        if (name === "") {
            document.myform.phone.removeAttribute("class", "ready");
            document.myform.phone.style.border = "1px solid #da3637";
            document.getElementById("telError").style.display = "block";
            document.getElementById("telErrorTwo").style.display = "none";
        } else {
                document.myform.phone.style.border = "1px solid #509d12";
                document.getElementById("telError").style.display = "none";
                var pattern = new RegExp("^\\d+$");
                var isValid = this.value.search(pattern) >= 0;

                if (!(isValid)) {
                    document.myform.phone.style.border = "1px solid #da3637";
                    document.getElementById("telErrorTwo").style.display = "block";
                } else {
                    document.getElementById("telErrorTwo").style.display = "none";
                    document.myform.phone.style.border = "1px solid #509d12";
                    document.myform.phone.setAttribute("class", "ready");
                }
            }
    };

    //filling the form
    document.myform.onchange = function() {
        var a = document.myform.name.getAttribute("class");
        var c = document.myform.phone.getAttribute("class");
        if (a === "ready" && c === "ready") {
            document.getElementById("save").removeAttribute("disabled");
            document.getElementById("save").style.cursor = "pointer";
            document.getElementById("save").style.opacity = "1";
        }
    };

【问题讨论】:

标签: javascript php jquery ajax


【解决方案1】:

使用 AJAX。我建议将您的表单编码为 JSON: 在 HTML 中:

<form name='myForm' onsubmit='event.preventDefault(); sendForm("myForm");'>...</form>

在 Js 中:

   function sendForm(formName){
      var http = new XMLHttpRequest();
      http.open("POST","YourPage.php");
      http.send(JSON.encodeForm(document.forms[formName]));
      http.onreadystatechange = function(){
        if(http.readyState == 4 && http.status == 200){
           console.log(http.responseText); //PHP page's response handling
        }
      }
    }
    JSON.encodeForm = function(form){
      var array = {};
      for (key in form) {
        var item=form[key];
        if(form.hasOwnProperty(key) && item == "[object HTMLInputElement]"){
          array[item.name]=item.value;
        }
      }
      return JSON.stringify(array);
    }

然后,在您的 PHP 页面中:

$input = json_decode(file_get_contents("php://input") , true);
echo "Saved";

【讨论】:

    【解决方案2】:

    我认为更好的选择是验证服务器端文件(some.php)中的数据并将响应返回到客户端文件。

    php code 将如下所示:

    $var = $_POST['some'];
    
    if($var (bla bla bla))
        { echo 'ok.'; } else { echo 'Error'; }
    

    您的 js 文件中的响应是来自您的 php 文件的回显消息。

    jsfiddle

    EDIT(添加输入掩码信息):

    如果您需要验证客户端文件中的输入,只需使用一些输入掩码库(例如 jquery input mask)。这将比创建自己的验证脚本更容易。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-20
      • 2014-08-10
      • 1970-01-01
      • 2013-08-20
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      相关资源
      最近更新 更多