为什么我将这个奇怪的JSON作为输出?

时间:2015-08-14 21:46:22

标签: javascript php jquery ajax json

我处理AJAX请求的PHP函数是

 $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("barryoabama@whitehouse.com","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添加到我的回调对象的末尾。

1 个答案:

答案 0 :(得分: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."}';