dongteng2534 2014-06-23 12:26
浏览 201
已采纳

如何从ajax回显json语句

my issue is as following,i have to display an error msg in 3 cases 1- some text is missing 2- telephone number should be all digits 3- email format is invalid the $errmsg is a JSON object that should display that message after being parsed in the ajax.but i don't know how to parse it in the ajax and return the value. here is my code:

$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;
 }

and the ajax code is as follows:

  $.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);     
       }        
    });
  • 写回答

4条回答 默认 最新

  • dtnbjjq51949 2014-06-23 12:31
    关注

    Try this:

    $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;
    }
    

    UPDATE

    If you want to parse the JSON data using jQuery, then can check the below code:

    <?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>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择
  • ¥15 这款软件是什么?需要能满足我的需求
  • ¥15 SpringSecurityOauth2登陆前后request不一致