在PHP或JS中提交表单后重定向到URL

时间:2015-07-21 22:33:23

标签: javascript php

重定向到“谢谢”是不是更好?在PHP或JS中提交表单时的页面。我不担心重定向之前页面上显示的任何文本。

我可能提供了太多代码,但我将在下面提供PHI和JS以供参考。

在我的BCC标题后,下面的标题是否会按预期工作?

header('Location: nextpage.html');
  

PHP

<?php   
if(empty($_POST['name2']) || empty($_POST['email2']) || empty($_POST['message2']))
{
    return false;
}

$name2 = $_POST['name2'];
$email2 = $_POST['email2'];
$message2 = $_POST['message2'];

$to = 'lindsay@domain.com'; // Email submissions are sent to this email

// Create email 
$email_subject = "Message from Domain 8.1";
$email_body = "You have received a new message. \n\n".
              "Name2: $name2 \nEmail2: $email2 \nMessage2: $message2 \n";
$headers = "From: lindsay@domain.com\r\n";
$headers .= "Reply-To: $email2\r\n";
$headers .= "Bcc: dan@domain.io\r\n";

mail($to,$email_subject,$email_body,$headers); // Post message
return true;            ?>
  

JS

&#13;
&#13;
$(function()
{
	var successMsg = "Your message has been sent."; // Message shown on success.
	var failMsg = "Sorry it seems that our mail server is not responding, Sorry for the inconvenience!"; // Message shown on fail.
	
	$("input,textarea").jqBootstrapValidation(
    {
     	preventSubmit: true,
     	submitSuccess: function($form, event)
	 	{
			event.preventDefault(); // prevent default submit behaviour
			
			var processorFile = "./bin/"+$form.attr('id')+".php";
			var formData = {};

			$form.find("input, textarea").each(function(e) // Loop over form objects build data object
			{		
				formData[$(this).attr('id')] = $(this).val();	
			});
	
			$.ajax({
		        url: processorFile,
		    	type: "POST",
		    	data: formData,
		    	cache: false,
		    	success: function() // Success
		 		{  
					$form.append("<div id='form-alert'><div class='alert alert-success'><button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;</button><strong>"+successMsg+"</strong></div></div>");		
		 	   	},
			   	error: function() // Fail
			   	{
					$form.append("<div id='form-alert'><div class='alert alert-danger'><button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;</button><strong>"+failMsg+"</strong></div></div>");	
			   	},
				complete: function() // Clear
				{
					$form.trigger("reset");
				},
		   	});
         },
         filter: function() // Handle hidden form elements
		 {
			 return $(this).is(":visible");
         },
	 });
});
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

成功时使用window.location

success: function() // Success
{  
    $form.append("");
    window.location = 'newURL.html';
}

答案 1 :(得分:1)

是的,标题应该重定向到nextpage.html,它应该在当前目录中。您应该在标题后面放置exit()调用,以确保在将标头发送到浏览器以进行重定向之前不会输出任何其他内容。所以最后你会得到

<?php
header('Location: nextpage.html');
exit();
?>

如果您没有放置退出调用并让脚本继续执行代码,则某些代码可能会生成输出,从而阻止重定向发生。

以上代码适用于PHP,因为JS使用window.location.href进行重定向。这看起来像这样

<script>
window.location.href = 'nextpage.html'
</script>