我知道以前曾经问过这个问题,而且我已经查看了我能找到的每个帖子。我仍然无法获得jQuery.post函数来正确地从PHP脚本接收错误。这两个都是。
PHP:
<?php
##CONFIGURATION
# LIST EMAIL ADDRESS
$toemail = "email here";
# SUBJECT (Subscribe/Remove)
$subject = "Someone has contacted International Designs";
# RESULT PAGE
$location = "../thank-you.php";
## FORM VALUES ##
$myname = $_REQUEST['myname'];
$myemail = $_REQUEST['myemail'];
$mymessage = $_REQUEST['mymessage'];
if ( empty($myname) || empty($myemail) || empty($mymessage) ) {
exit('{"error":"That value was invalid!"}')
} else {
# SENDER
$email = $myname . " <" . $myemail . ">";
# MAIL BODY
$body .= "Name: " . $myname . " \n\n";
$body .= "Email: " . $myemail . " \n\n";
$body .= "Message: " . $mymessage . " \n\n";
# add more fields here if required
## SEND MESSGAE ##
mail( $toemail, $subject, $body, "From: $email" ) or die ("Mail could not be sent.");
}
?>
JS:
if (verify(myname, myemail, mymessage, human, hash, patt)) {
$.post(myform.attr('action'), myform.serialize(), function() {
$('#email-success').fadeIn();
myform[0].reset();
setTimeout("$('#email-success').fadeOut();", 5000);
}, 'json')
.fail(function() {
alert('An error has occurred. Please try again later.')
});
}
我已经尝试过5种不同的方法,但都没有。当我把&#39; json&#39;作为.post函数中的数据类型,.fail 总是触发,无论php脚本中有什么内容。如果我保留数据类型,那么.fail 永远不会在任何情况下触发。我有一种感觉问题是php命令和数据类型。任何帮助表示赞赏。
答案 0 :(得分:2)
也许是因为您没有更改回复的http标头代码,也没有指定您的数据类型响应。
你使用&#34; 200来对前端(jQuery)代码进行php代码响应 - OK&#34;在任何情况下都是状态,但是在某些情况下,您会发现错误,其中包含&#39; HTTP / 1.0 400 - 错误请求&#39;响应或“HTTP / 1.0 500内部服务器错误&#39;。
”而且,像Eggplant一样,您必须将响应数据类型指定为&#39; Content-Type:application / json&#39;。
所以,最终的代码是这样的:
<?php
...
header('HTTP/1.0 204 – No Content', true, 204);
header('Content-Type: application/json');
if ( empty($myname) || empty($myemail) || empty($mymessage) ) {
header('HTTP/1.0 400 – Bad Request', true, 400);
exit('{"error":"That value was invalid!"}')
} else {
...
$send = mail( $toemail, $subject, $body, "From: $email" );
if (!$send)
header('HTTP/1.0 500 – Internal Server Error', true, 500);
exit ('{"error":"Mail could not be sent."}');
}
}
return;
?>
对于警告Cannot modify header information - headers already sent by (output started at /homepages/.../design/contact.php:1)
,您可以检查同一问题的this answer。
输出可以是:
聊天会话后更新:它是UTF-8 BOM问题
答案 1 :(得分:0)
虽然你的是一个有效的JSON数据,我总是建议使用json_encode()函数来创建JSON字符串。
exit(json_encode(array("error" => "That value was invalid!")));
另一个是确保发送正确的标头以确保脚本知道它的json数据。所以
header('Content-Type: application/json');
exit(json_encode("error" => "That value was invalid!"));
答案 2 :(得分:0)
试试这个
if (verify(myname, myemail, mymessage, human, hash, patt)) {
$.ajax({
type :'POST',
data :$("#myformid").serialize(),
beforeSend:function(){
},
success:function(res){
if(res=='ok'){
setTimeout("$('#email-success').fadeOut();", 5000);
}else{
//read respon from server
alert(res)
}
},
error:function(){
//error handler
}
});
}
只是示例
$send = mail(....);//your mail function here
echo ($send) ? "ok" : "Error";