代码之家  ›  专栏  ›  技术社区  ›  AskaNor_29

提交表单后的纯Javascript Ajax请求

  •  0
  • AskaNor_29  · 技术社区  · 7 年前

    我不太擅长编程,我正在尝试制作一个联系表单,并在同一页中发送带有回复的信息。

    <form id="contact_form" method="post" action="send.php">
    
    // fields
    
    </form>
    

    邮寄php包含一个PHPMailer函数来发送邮件和其他控件,因此如果禁用js,用户将被重定向到索引。带有成功或错误消息的php。

    但是当js处于活动状态时,验证函数会检查所有字段是否已填充,然后启动ajax请求,这是js中的代码。js文件

    function validate(e) {
        if (error_type === 1) {
                e.preventDefault();
                // display errors for every fields
            } else {
    
                var url = "send.php";
                var params = fileds_value;
                xhttp = new XMLHttpRequest();
                xhttp.open("POST", "url", true);
                xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                xhttp.onload = function() {
                    if (xhttp.readyState == 4 && xhttp.status === 200 && xhttp.responseText) {
                        //display success message
    
                    }
                    else if (xhttp.status !== 200 || !xhttp.responseText) {
                        //display error message
    
                    }
                };
                xhttp.send(JSON.stringify(params));
             }
    
        }}
    window.onload = function() {
        document.getElementById("contact_form").addEventListener("submit", function(e){
            validate(e);
        });
    };
    

    我需要将表单数据与请求一起发送,以防止页面被刷新,对吗?

    和发送中。php

    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'XMLHttpRequest') {
    
      header('Content-Type: application/x-www-form-urlencoded');
      echo $ajax_message;
    }
    // else just display the message
    else {
    
      redirect_to($message);
    }
    

    但在按下提交按钮后,页面被重新加载,我看到了PHP成功消息,我的目标是使用ajax使页面显示成功消息,而无需重新加载页面。

    编辑:@IncredibleHat我编辑了代码来显示事件是如何处理的,所以我必须始终防止默认行为,并像那样发送表单数据,然后在php中我可以像往常一样获取post变量?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Osvaldo Maria    7 年前

    使用 event.preventDefault(); ,而不是将其包装在条件中。

    如果表单位于其他html元素中,请尝试 event.stopPropagation(); ,因为它阻止事件冒泡并由父元素的侦听器处理

    最后,你会得到如下结果:

    form.addEventListener('submit',function(){
        event.preventDefault();
        event.stopPropagation();
    
        if (error_type === 1) 
             //doWhatever
        //..... perform ajax request
    })