我遇到一个问题,我的AJAX表单帖子创建了一个警报,似乎回显整个页面,而不仅仅是成功消息,我无法弄清楚我做错了什么.另外,我已经跟踪了很多关于堆栈的技巧,通过序列化传递数据,但是我习惯了这样的事情,data { action: add, type: new }并且我有问题将其他变量附加到post请求到数据,因为$(this).serialize();
PHP
if (isset($_POST['type']) && $_POST['type'] == 'email') {
$emailFrom = EMAIL_FROM;
$email_to = $_POST['email_to'];
$subject = $_POST['subject'];
$body = $_POST['body'];
if (mail($email_to, $subject, $body, "From: <$emailFrom>")) {
return 'Email was successfully sent!';
} else {
return 'An error occured, email could not be sent.';
}
exit();
}
Run Code Online (Sandbox Code Playgroud)
JS
<script>
$(document).ready(function() {
$("#user_email").submit(function(e) {
var subject = $('#subject').val();
var _body = $('#body').val();
if (_body && subject) {
$.ajax({
type: "POST",
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(data)
{
alert(data);
}
});
} else {
alert ('Subject and Body fields are both required.');
}
e.preventDefault();
});
});
</script>
Run Code Online (Sandbox Code Playgroud)
HTML
<h3>Send <?php echo $row_users['full_name'];?> an email</h3>
<div class="ec-messages messages-warning" style="width:300px;">Emails will be sent from the website default.</div>
<form action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="post" name="user_email" id="user_email">
<input name="email_to" type="hidden" value="<?php echo $row_users['user_email'];?>">
<label>Subject</label><input type="text" name="subject" id="subject">
<label>Body</label><textarea name="body" id="body" rows="10" class="span5"></textarea>
<?php echo createFormButtons(true, true); ?>
</form>
Run Code Online (Sandbox Code Playgroud)
if (isset($_POST['type']) && $_POST['type'] == 'email') {
}
Run Code Online (Sandbox Code Playgroud)
那么上述条件会发现,如果名称type和值为'email' 的字段存在与否
由于您的ajax请求作为整个HTML提供响应,这意味着此条件不符合
只需在表单中添加以下行
<input type='hidden' name='type' value='email' />
Run Code Online (Sandbox Code Playgroud)
如果这对你有用,请告诉我