简体   繁体   English

请求的 JSON 解析失败 (jquery+ajax)

[英]Requested JSON parse failed (jquery+ajax)

Hello i've got a json parse error.您好,我遇到了 json 解析错误。 This is simple jquery+ajax+php code that validates a data that user inputs into contact form.这是一个简单的 jquery+ajax+php 代码,用于验证用户输入到联系表单中的数据。

jq+ajax: jq+ajax:

$(document).ready(function() {
$("#cbutton").click('submit', function(e) {
    e.preventDefault();
    var name = $("#fname").val();
    var email = $("#fmail").val();
    var phone = $("#fphone").val();
    var message = $("#fmess").val();

    if (name == '' || email == '' || phone == '' || message == '') {
        console.log("Please Fill Required Fields");

    }
    $.ajax({
        method: "POST",
        contentType:"application/json",
        url: "php/some.php",
        dataType: "json",
        data: { 
            name: 'name', 
            email: 'email',
            phone: 'phone', 
            message: 'message',
        },
        success : function(data){
            // if (data.code == "200"){
                // console.log("Success: " +data.msg);
            // }
            $.each(data, function(index, element) {

                console.log("Success: " +element.name);

            });
        },
        error: function(jqXHR, exception) {
            if (jqXHR.status === 0) {
                alert('Not connect.\n Verify Network.');
            } else if (jqXHR.status == 404) {
                alert('Requested page not found. [404]');
            } else if (jqXHR.status == 500) {
                alert('Internal Server Error [500].');
            } else if (exception === 'parsererror') {
                alert('Requested JSON parse failed.');
            } else if (exception === 'timeout') {
                alert('Time out error.');
            } else if (exception === 'abort') {
                alert('Ajax request aborted.');
            } else {
                alert('Uncaught Error.\n' + jqXHR.responseText);
            }
        }
    });
});

}); });

and php:和PHP:

<?php

header('Content-Type: application/json');

$errorMSG = "";

if (empty($_POST["name"])) 
    $errorMSG = "<li>Name is required</<li>";
} else {
    $name = $_POST["name"];
}

if (empty($_POST["email"])) {
    $errorMSG .= "<li>Email is required</li>";
} else if (!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
    $errorMSG .= "<li>Invalid email format</li>";
} else {
    $email = $_POST["email"];
}

if (empty($_POST["phone"])) {
    $errorMSG = "<li>Phone is required</<li>";
} else {
    $name = $_POST["phone"];

}
if (empty($_POST["message"])) {
    $errorMSG .= "<li>Message is required</li>";
} else {
    $message = $_POST["message"];
}


if (empty($errorMSG)) {
    $msg = "Name: " . $name . ", Email: " . $email . ", Phone: " . $phone . ", Message:" . $message;
    //echo json_encode(['code'=>200, 'msg'=>$msg]);
    echo $msg;
    exit;
}
?>

I've tried to fix it with a several methods (as you see by comments) and nothing's working.我试图用几种方法来修复它(正如你在评论中看到的),但没有任何效果。 Script should create json and check if data is correct (correct email and no blank spots).脚本应该创建 json 并检查数据是否正确(正确的电子邮件并且没有空白点)。

message: 'message', 最后一个逗号必须去掉

In your ajax request, you have set return data type to JSON, so you can only send JSON data, try following, it will work.在您的ajax请求中,您已将返回数据类型设置为JSON,因此您只能发送JSON数据,请尝试以下操作,它将起作用。

if(empty($errorMSG)){
    $msg = "Name: ".$name.", Email: ".$email.", Phone: ".$phone.", 
    Message:".$message;

    $result = array();
    $result['code'] = 200;
    $result['msg'] = $msg;

    echo json_encode($result);
    exit;
}

Your php file is not returning valid JSON response even though you set response header as header('Content-Type: application/json') in case of failure.即使您将响应标头设置为 header('Content-Type: application/json') 以防万一,您的 php 文件也不会返回有效的 JSON 响应。 php file should echo valid JSON string like below. php 文件应该回显如下有效的 JSON 字符串。

$errorMSG = "{errMsg: 'Name is required'}"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM