我的问题如下,我必须在3种情况下显示错误信息 1-缺少一些文字 2-电话号码应为所有数字 3-电子邮件格式无效 $ errmsg是一个JSON对象,应该在ajax中解析之后显示该消息。但是我不知道如何在ajax中解析它并返回值。 这是我的代码:
$errmsg='{"invalid":"some text missing",
"mailerr":"email format is incorrect",
"telephoneerr":"telephone should be all digits"}';
if(($name=="")||($email=="")||($telephone=="")||($username=="")||($password==""))
{
echo $errmsg;
}elseif(!preg_match($pattern_email,$email)){
echo $errmsg;
}
elseif (!preg_match($pattern_phone,$telephone)){
echo $errmsg;
}
和ajax代码如下:
$.ajax({
type:'POST',
url: 'contactData.php',
//dataType: "JSON",
data{"name":name,"telephone":telephone,"email":email,"username":username,"password":password},
success: function(data) {
$("#validate").html(data);
}
});
答案 0 :(得分:0)
您可以在ajax(在jQuery中)使用“dataType:JSON”而不是
$errmsg='{"invalid":"some text missing",
"mailerr":"email format is incorrect",
"telephoneerr":"telephone should be all digits"}';
在php
中返回一个带有json_encode的数组echo json_encode(array("invalid" => "some text missing",
"mailerr" => "email format is incorrect",
"telephoneerr" => "telephone should be all digits"));
现在您可以像
这样的对象访问数组值data.invalid OR data.mailerr
答案 1 :(得分:0)
试试这个:
$errmsg='{"invalid":"some text missing",
"mailerr":"email format is incorrect",
"telephoneerr":"telephone should be all digits"}';
if (($name == "") || ($email == "") || ($telephone == "") || ($username == "") || ($password == "") || !preg_match($pattern_email, $email) || !preg_match($pattern_phone, $telephone)){
return $errmsg;
}
如果要使用jQuery解析JSON数据,可以查看以下代码:
<?php
if (($name == "") || ($email == "") || ($telephone == "") || ($username == "") || ($password == "")) {
$errorMsg = array("error" => "some text missing");
} elseif (!preg_match($pattern_email, $email)) {
$errorMsg = array("error" => "email format is incorrect");
} elseif (!preg_match($pattern_phone, $telephone)){
$errorMsg = array("error" => "telephone should be all digits");
}
return json_encode($errorMsg);
?>
<script>
$.ajax({
type:'POST',
url: 'contactData.php',
dataType: "JSON",
data{"name":name, "telephone":telephone, "email":email, "username":username, "password":password},
success: function(data) {
data = jQuery.parseJSON(data);
$("#validate").html(data.error);
}
});
</script>
答案 2 :(得分:0)
看起来你的JSON形成得很糟糕。尝试在没有外部单引号的情况下编写它,如下所示:
$errmsg = {
"invalid" : "some text missing",
"mailerr" : "email format is incorrect",
"telephoneerr" : "telephone should be all digits"
};
然后调用$errmsg['invalid']
等来获取每个案例所需的错误消息。
答案 3 :(得分:0)
我认为你的输出是正确的,你需要在jquery中显示
$.ajax({
type:'POST',
url: 'contactData.php',
//dataType: "JSON",
data{"name":name,"telephone":telephone,"email":email,"username":username,"password":password},
success: function(data) {
var obj = jQuery.parseJSON(data);
$("#validate").html(obj.invalid);
}
});