jQuery失败:抛出错误的parsererror:SyntaxError:JSON输入的意外结束

时间:2017-11-11 14:58:11

标签: php jquery json ajax

我有一个联系表单,通过ajax传递给PHP脚本。处理完表单后,ajax将根据从PHP脚本中的json_encode()函数收到的响应执行一些操作。问题是我收到以下错误消息:

  

parsererror SyntaxError:JSON输入的意外结束

     

readyState:4 responseText:“”status:200 statusText:“OK”

dataType是ajax调用中的文本而PHP脚本只是回显一条文本消息时,代码工作正常,但是使用json,我得到了上述错误。

我尝试过标题("Content-Type: application/json")和JSON.parse()但没有成功。我在标题中添加了charset="UTF-8",并在传递给encode_utf8()的数组上尝试了json_encode函数,但似乎对我没什么用。

我发布以下相关文件的代码。任何有助于解决此问题的帮助都将受到高度赞赏。

contact.php

<form action="" method="post" name="contactForm" id="contactForm">   

    <div class="form-row">         
        <div id="contactFormResponse"></div>

        <div class="form-col">  
            <label for="orderNumer">Order Number</label>
            <input type="text" name="orderNumber" id="orderNumber" value="<?php echo ($_POST['orderNumber']); ?>" />
        </div>

        <div class="form-col">
          <label for="comment">Comment *</label>
          <textarea name="message" id="comment" maxlength="2000" rows="5"><?php echo ($_POST['comment']); ?></textarea>
        </div>

        <div class="form-col">
            <label for="title">Title *</label>
            <select name="title" id="title">
                <option value="" <?php if ($_POST['title'] == "") {echo "selected='selected'";} ?>>Select a title...</option>
                <option value="ms" <?php if ($_POST['title'] =="ms") {echo "selected='selected'";} ?>>Ms</option>
                <option value="miss" <?php if ($_POST['title'] == "miss") {echo "selected='selected'";} ?>>Miss</option>
                <option value="mrs" <?php if ($_POST['title'] == "mrs") {echo "selected='selected'";} ?>>Mrs</option>
                <option value="mr" <?php if ($_POST['title'] == "mr") {echo "selected='selected'";} ?>>Mr</option>
                <option value="other" <?php if ($_POST['title'] == "other") {echo "selected='selected'";} ?>>Other</option>
            </select>
        </div>

        <div class="form-col">
            <label for="firstName">First Name *</label>
            <input type="text" name="firstName" id="firstName" value="<?php echo ($_POST['firstName']); ?>" />
        </div>

        <div class="form-col">
            <label for="surname">Surname *</label>
            <input type="text" name="surname" id="surname" value="<?php echo ($_POST['surname']); ?>" />
        </div>

        <div class="form-col">
            <label for="email">Email Address *</label>
            <input type="text" name="email" id="email" value="<?php echo ($_POST['email']); ?>" />
        </div>

        <div class="form-col">
            <input type="submit" name="submitContactForm" id="submitContactForm" value="Submit" class="btn" />
        </div>

    </div>
</form>

jsCode.js

// process contact form
$("#contactForm").submit(function(e) {

    e.preventDefault();

    // some jQuery validation goes here...

    $.ajax({
        type:"POST",
        url: "functions.php",
        dataType: "json",
        data: new FormData(this),
        //data: $('form').serialize(),
        processData: false,
        contentType: false,
        success:function(response) {
            if(response.status === "OK") {
                $("#contactFormResponse").html("<div class='alert alert-success' id='message'></div>");
                $("#message").html(response.message).fadeIn("100");
                $("#contactForm")[0].reset();
                $(window).scrollTop(0); 
            } else if (response.status === "error") {
                $("#contactFormResponse").html("<div class='alert alert-danger' id='message'></div>");
                $("#message").html(response.message).fadeIn("100");
                $(window).scrollTop(0);
            }  
       },
       error:function(jqXHR, textStatus, errorThrown) {
           console.log("JQuery failed: " + textStatus + " with error thrown: " + errorThrown);
           console.log(jqXHR);

         }
    });
});

的functions.php

// send email
function sendMessage() {

    if (isset($_POST["submitContactForm"])) {
        if (!$_POST["comment"]) {
            $error .= "<br />Comment is required.";
        }

        if (!$_POST["firstName"]) {
            $error .= "<br />First name is required.";
        }

        // validation for other form fields goes here... 

        if ($error) {
            echo json_encode(array("status" => "error", "message" => "There were error(s)in your form: " . $error));

        } else {

            $to            = "email@domain.com";
            $subject       = "Message from the website";
            $order_number  = $_POST["orderNumber"];
            $comment       = $_POST["comment"];
            $title         = $_POST["title"];
            $first_name    = $_POST["firstName"];
            $surname       = $_POST["surname"];
            $email_address = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
            $headers       = "From: " . $title  . " "  . $first_name . " " . $surname . " <" . $email_address . " >";
            $message       = "Order Number: " . $order_number . "/r/n" . "Topic: " . $topic . "/r/n" . "Comment: " . $comment;

            $result = mail($to, $subject, $message, $headers); 

            if (!$result) {

                echo json_encode(array("status" => "error", "message" => "Message failed."));

            } else {

               echo json_encode(array("status" => "OK", "message" => "Message sent."));

            }  
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您没有在success函数中解析json响应,您需要使用$.parseJSON(response),如下所示

    success:function(res) {
var response=$.parseJSON(res);
                if(response.status === "OK") {
                    $("#contactFormResponse").html("<div class='alert alert-success' id='message'></div>");
                    $("#message").html(response.message).fadeIn("100");
                    $("#contactForm")[0].reset();
                    $(window).scrollTop(0); 
                } else if (response.status === "error") {
                    $("#contactFormResponse").html("<div class='alert alert-danger' id='message'></div>");
                    $("#message").html(response.message).fadeIn("100");
                    $(window).scrollTop(0);
                }  
           },