parsererror SyntaxError:JSON

时间:2017-01-19 16:31:29

标签: javascript php jquery json ajax

我一直在尝试使用Ajax从联系表单发送电子邮件。

发送邮件时,应返回确认消息: “谢谢你联系我们。”

我没有显示此消息,而是出错:

{"type":"success","message":"thank you for contacting us"} parsererror    SyntaxError: Unexpected number in JSON at position 8
at JSON.parse (<anonymous>)
at parseJSON (jquery.js:4)
at On (jquery.js:6)
at k (jquery.js:6)
at XMLHttpRequest.r (jquery.js:6)`

这是发送邮件的PHP文件:

<?php
require_once 'phpmailer/PHPMailerAutoload.php';

$okMessage = 'thank you for contacting us';


$name = @trim(stripslashes($_POST['name'])); 
$email = @trim(stripslashes($_POST['email'])); 
$subject = @trim(stripslashes($_POST['subject'])); 
$message = @trim(stripslashes($_POST['message'])); 
$societe = @trim(stripslashes($_POST['societe']));
$num = @trim(stripslashes($_POST['num']));

$body = 'Name: ' . $name . "\n\n" . 'Entreprise: ' . $societe . "\n\n" . 'contact Tel: ' . $num . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;

$mail = new PHPMailer();

$mail->IsSMTP();
$mail->Host = 'xxxxx'; 
$mail->Port = xx; //
$mail->CharSet = 'UTF-8';
$mail->SMTPAuth = true; 
$mail->SMTPDebug = 2; 
$mail->Username = "xxxx"; 
$mail->Password = "xxxx"; 


$mail->setFrom('xxxx','xxxx'); 
$mail->addAddress('xxxx'); 
$mail->Subject = $subject;
$mail->Body = $body;
$mail->send();

header('Content-type: application/json');
$status = array(
'type' => 'success',
'message' => $okMessage
);
echo json_encode($status);
die;

这是我的JS功能

var form = $('#main-contact-form');
form.submit(function(event){
    event.preventDefault();
    var form_status = $('<div class="form_status"></div>');

    var req = $.ajax({
                url: $(this).attr('action'),
                type: "POST",
                data: form.serialize(),
                dataType : 'json',
                beforeSend: function(){
                    form.prepend( form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn() );
                }
    });

    req.done( function( data, textStatus, jqXHR ){

        console.log( data, textStatus, jqXHR );
        console.warn( jqXHR.responseText);
        form_status.html('<p class="text-success">' + data.message + '</p>').delay(3000).fadeOut();
    });

    req.fail( function( jqXHR, textStatus, errorThrown ){
        console.log( jqXHR.responseText, textStatus, errorThrown );
        console.warn( jqXHR.responseText);
        form_status.html('<p class="text-error">' + textStatus + '</p>').delay(3000).fadeOut();
    });
});

你能帮我吗?

1 个答案:

答案 0 :(得分:1)

我已经解决了这个问题。

在浏览器的网络标签中,我看到响应不仅仅是Json。

我意识到它是由参数

引起的
$mail->SMTPDebug = 2;

事实上,在用JSON打印响应之前,它返回了Server和Client之间的整个对话。 所以我用

替换它
$mail->SMTPDebug = 0;

现在一切都很好。

感谢您的帮助