这是使用
suggested example from the JQuery site和
pajaja’s答案的工作示例.
解:
将其放在< head>中.你的网页.
< script src =“http://code.jquery.com/jquery-1.10.1.min.js”>< / script>
要么
下载JQuery并以相同的方式包含它.
形成:
您的联系表格保持不变.
Your Name
Email Address
Message
Send
退货数据:
将您的响应元素添加到正文中.
< div id =“contactResponse”>< / div>
使用Javascript:
现在放置(最好在< / body>之前)javascript代码:
$("#contactForm").submit(function(event)
{
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
$submit = $form.find( 'button[type="submit"]' ),
name_value = $form.find( 'input[name="name"]' ).val(),
email_value = $form.find( 'input[name="email"]' ).val(),
message_value = $form.find( 'textarea[name="message"]' ).val(),
url = $form.attr('action');
/* Send the data using post */
var posting = $.post( url, {
name: name_value,
email: email_value,
message: message_value
});
posting.done(function( data )
{
/* Put the results in a div */
$( "#contactResponse" ).html(data);
/* Change the button text. */
$submit.text('Sent, Thank you');
/* Disable the button. */
$submit.attr("disabled", true);
});
});
动作脚本:
您的联系人(PHP)文件保持不变,但将$_GET更改为$_POST:
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$to = "xxx@xxx.xxx";
$subject = "";
$message = "";
$headers = "From: $email";
if( mail($to,$subject,$message,$headers) )
{
echo "
Thank you for your comment
";}
else
{
echo "
Sorry, there has been an error
";}
?>
结果:
现在应该在提交时从表单发送数据,然后在#contactResponse元素中显示返回的数据.该按钮还将文本设置为“已发送,谢谢”,同时也禁用该按钮.