为什么我得到这个奇怪的JSON作为输出?
问题描述:
我的PHP函数来处理Ajax请求为什么我得到这个奇怪的JSON作为输出?
$nameMap = array('name' => 'Name', 'email' => 'Email Address', 'phone' => 'Phone Number', 'comments' => 'Comments');
// https://css-tricks.com/sending-nice-html-email-with-php/
$headers = "MIME-Version: 1.0\r\nContent-Type: text/html; charset=ISO-8859-1\r\n";
function contact ()
{
global $nameMap, $headers;
$emailMsg = '<html><body><h3>Someone submitted a contact form ...</h3><table>';
foreach ($_POST as $key => $value) if (array_key_exists($key, $nameMap)) $emailMsg .= '<tr><td><b>' . $nameMap[$key] . ':</b></td><td>' . $value . '</td></tr>';
$emailMsg .= '</table></body></html>';
if (mail("[email protected]","A Comment Was Submitted",$emailMsg,$headers))
{
echo json_encode(array('succeeded' => true, 'msg' => 'Your comment was submitted successfully!'));
}
else
{
echo json_encode(array('succeeded' => false, 'msg' => 'There was a problem with the info you submitted.'));
}
}
,我的JavaScript是
$('.contact-form .contact-submit-btn').click(function(e){
formdata = new FormData($(this).closest('.contact-form')[0]);
formdata.append('action', 'contact');
$.ajax({
url: ajaxurl,
type: 'POST',
data: formdata,
async: false,
success: function (retobj) {
console.log(JSON.stringify(retobj)); // TEST
if (retobj.succeeded)
{
$('.contact-form h1').text('Your email was submitted successfully!');
$('.contact-form input[type="text"]').hide();
}
else
{
$('.contact-form h1').text('Your email was not submitted successfully!');
}
},
error: function() {
// haven't decided what to do yet
},
cache: false,
contentType: false,
processData: false
});
});
并进入PHP脚本的else
块时(我不知道该if
块因为我没有能够进去那里哈哈)我看到
"\r\n\r\n0"
打印到控制台,而我期望看到
{"succeeded":true,"msg":"There was a problem with the info you submitted."}
这些字符都来自哪里?尤其是0
...自从我开始学习PHP以来,我总是得到一个0
添加到我的回调对象的末尾。
答
你的PHP没有返回任何东西。
试试这个: 修改内容类型为application/JSON
$headers = "MIME-Version: 1.0\r\nContent-Type: application/json; charset=ISO-8859-1\r\n";
,这增加了尽头......
echo '{"succeeded":true,"msg":"There was a problem with the info you submitted."}';
所以开始调试:垃圾你的代码调试输出和看看事情在哪里/何时执行。 –
你为什么要用'json.stringify'? –
尝试将标题替换为'header('Content-Type:application/json');'编辑:实际上,请尝试设置标题,因为该标题仅用于邮件。 – Berriel