您好我有一个json解析错误。这是简单的jquery + ajax + php代码,用于验证用户输入联系表单的数据。
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);
}
}
});
});
});
和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;
}
?>
我尝试用几种方法修补它(正如你所看到的那样)并且没有任何工作。脚本应该创建json并检查数据是否正确(正确的电子邮件,没有空白点)。
答案 0 :(得分:1)
消息:“消息”, 最后一个逗号必须删除
答案 1 :(得分:-2)
即使您将响应标头设置为标头(&#39; Content-Type:application / json&#39;),您的php文件也不会返回有效的JSON响应。 php文件应该回显有效的JSON字符串,如下所示。
$errorMSG = "{errMsg: 'Name is required'}"
答案 2 :(得分:-2)
在您的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;
}