【发布时间】:2017-09-27 19:56:19
【问题描述】:
我尝试了许多来自 stackoverflow.com 的示例 jQuery ajax success error
但总是给我错误。
每当我在代码下面运行时,如果 ajax 代码错误,则 ajax 会显示错误消息,但是当 php 有错误代码时,ajax 总是显示 success: function (data) code。
据我所知 data.status == 'success' 没有从 php 进行比较,所以我的代码给出了错误
我知道这个问题是重复的,但我从 stackoverflow 看到了所有问题,这些问题并不能解决我的问题,所以我再次发布
请帮忙
AJAX 代码
$(document).ready(function () {
$(function () {
$('.contactf').submit(function (e) {
e.preventDefault();
if (!contactvalid())
return false;
$(this).find(":submit").prop("disabled", true);
$('#gif').css('display', 'block');
var form = $(this);
var post_url = 'contactmail1.php';
var post_data = form.serialize();
$.ajax({
type: 'POST',
url: post_url,
data: post_data,
success: function (data) {
if (data.status == 'success') {
alert(data);
} else if (data.status == 'error') {
alert(data);
}
},
error: function (data) {
alert('failed client side');
}
});
});
});
});
PHP
<?php
//
header('Content-type: application/json');
if ( $_SERVER[ 'REQUEST_METHOD' ] == 'POST' ) {
require 'phpmailer/PHPMailerAutoload.php';
$name = $_POST[ 'Name' ];
$email = $_POST[ 'Email' ];
$phone = $_POST[ 'number' ];
$sub = $_POST[ 'contact_subject' ];
$msg = $_POST[ 'Message' ];
if ( !( isset( $_POST[ 'Name' ] )and isset( $_POST[ 'Email' ] )and isset( $_POST[ 'number' ] )and isset( $_POST[ 'contact_subject' ] )and isset( $_POST[ 'Message' ] ) ) ) {
echo "Some Field is Blank";
} else {
$mail = new PHPMailer;
$mail->setFrom( $email, $name );
$mail->addAddress( 'mail@gmail.com', 'Inderjeet' );
$mail->Subject = 'Mail from site';
$mail->msgHTML( '<html><body><table border=0 width=554><tr><td colspan=2><p><b>Enquiry from Contact Page Thorsoncne.com</b><br><br></p></td></tr><tr><td colspan=2 class=text4>FORM submitted at ' . date( 'd F Y h:i:s A' ) . '<br></td></tr>
<tr><td width=200 class=text3>Name :</td><td class=text3>' . $name . '</td></tr>
<tr><td>Email Id :</td><td>' . $email . '</td></tr>
<tr><td>Phone/Mobile :</td><td>' . $phone . '</td></tr>
<tr><td>Subject :</td><td>' . $sub . '</td></tr>
<tr><td>Message :</td><td>' . $msg . '</td></tr>
</table></body></html>' );
if ( !$mail->send() ) {
$response_array['status'] = 'failed';
echo "Mailer Error: " . $mail->ErrorInfo;
echo json_encode($response_array);
} else {
$response_array['status'] = 'success';
echo json_encode($response_array);
echo "Query Submitted";
}
}
}
【问题讨论】:
-
在
echo json_encode($response_array);之后删除echo "Query Submitted"; -
不要使用截图,请将代码复制到问题中
-
和 JSON 编码
"Some Field is Blank";或使用 $response_array['status'] = 'blank'; -
并在帖子中添加
dataType: "json" -
您必须对整个响应进行编码,而不仅仅是对其中的一部分进行编码,否则返回给客户端的最终结果将不是有效的 JSON。您当前通过“echo”直接输出的字符串需要合并到编码对象中(或者删除,如果它们是多余的)。你没有说它给了你什么错误,但我猜它是关于无效 JSON 的。