如果使用ajax调用提交联系表单,则标题(位置:/路径)不起作用

时间:2019-04-02 06:34:52

标签: javascript php

问题是,如果尝试通过ajax致电提交我的联系表。 then header("location: /path);开始不起作用。

if ($response->success) {
      $guest = mail($serverMail, $toAdmin, $mailMessageToServer, $headers);
      $server = mail($email, $toGuest, $mailMessageToGuest, $headers);
      if (($guest) && ($server)) {
        // header("location: /contact/thankyou.html");
      } 
  } else {
    echo "Invalid captcha! Please enter again. ";
  }

是的,因为标头重定向不起作用。我将其注释掉。并尝试在ajax调用中重定向页面,如下所示。

$(document).ready(function() {
    var form = $('#mailformpro');
    var response = $('.status');
    form.on('submit', function(e) {
        e.preventDefault();
        $.ajax({
            url: 'contactform/ajax/contact.php',
            type: 'POST',
            dataType: 'html',
            data: form.serialize(),
            beforeSend: function(){
                response.fadeOut();
                response.fadeIn();
                response.html('Loading...');
            },
            success: function(data){
                response.html(data).fadeIn();
                window.location.href ="/contact/thankyou.html";
            },
            error: function(e){
                console.log(e)
            }
        });
    });
    });

但这一次,它仅在.status div内重定向!就像在image中一样,通常我在该div中显示一条错误消息...

2 个答案:

答案 0 :(得分:1)

嘿,这是错误的做法,如果您使用的是ajax req,则php无法将其重定向到目的地,您需要在ajax成功响应中进行重定向,这很简单

$data = array();
if ($response->success) {
    $guest = mail($serverMail, $toAdmin, $mailMessageToServer, $headers);
    $server = mail($email, $toGuest, $mailMessageToGuest, $headers);
    if (($guest) && ($server)) {
        $data['status'] = 1; // for true
        $data['message'] = "your success message"; // for true
    }
} 
else {
    $data['status'] = 0; // for false
    $data['message'] = "your error message"; // for false
}
//define content type json if you never echo like echo 'ss' then no need to this
header('Content-Type: application/json');
echo json_encode($data);exit;

并在ajax请求数据类型Json中获取响应以访问json数组obj

$(document).ready(function() {
  var form = $('#mailformpro');
  var response = $('.status');
  form.on('submit', function(e) {
    e.preventDefault();
    $.ajax({
      url: 'contactform/ajax/contact.php',
      type: 'POST',
      dataType: 'json',
      data: form.serialize(),
      beforeSend: function() {
        response.fadeOut();
        response.fadeIn();
        response.html('Loading...');
      },
      success: function(data) {
        if (data.status == 1) {
        response.html(data.message).fadeIn();
        window.location.href = "/contact/thankyou.html";
        }
        else{
        // for error
        response.html(data.message).fadeIn();
        }
      },
      error: function(e) {
        console.log(e)
      }
    });
  });
});

答案 1 :(得分:0)

您必须将标头作为Base64字符串发送,然后在服务/后端中对其进行解码。