根据条件在JQUERY / AJAX中访问JSON值

时间:2018-10-15 10:06:03

标签: php jquery ajax

请耐心等待,因为我知道可能已经回答了这个问题,但是我找不到它。我一直在从事一个项目,最近我才刚开始使用AJAX。

我的JSON来自PHP,其中包括错误和成功,现在的问题是如何访问成功(如果注册成功显示为Text(非警报))并在注册失败时显示错误。

应使用什么条件?

<div class="remodal" data-remodal-id="RegisterModal">
  <div class="popup-1">
      <div class="popup-content" id="register_container">
          <div id="register_title" class="popup-title text-purple">Sign Up</div>
          <div class="reg-notification">
              <p>You Successfully registered to our website and now you can login and use our services</p>
              <a href="feed.php" class="popup-link">Continue</a>
          </div>
          <div id="json"></div>
          <form id="register-form" action="register.php" method="POST">
              <div class="form-grp">
                  <!--<label>Username</label>-->
                  <input type="text" id="username" name="username" placeholder="Username">
              </div>
              <div class="form-grp">
                  <input type="email" name="register_email" id="register_email" placeholder="Email">
              </div>
              <div class="form-grp">
                  <input type="password" id="register_password" name="register_password"  placeholder="Password">
              </div>
              <div class="form-grp">
                  <input type="password" id="confirm_password" name="confirm_password"  placeholder="Retype Password">
              </div>
              <div class="btn-grp">
                  <button type="submit" name="submit" class="button-purple" id="do_register">Sign Up</button>
                  <button class="button-white" style="margin-left: 30px;" data-remodal-target="LoginModal">Login to access</button>
              </div>
          </form>
      </div>

这是我下面的PHP

  if (strlen($password) >= 8 && strlen($password) <= 60) {


                    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
                        $account->addUser($username, $password, $email);
                        if ($account->userExist()) {
                            $message['email'] = "Email Address Is Already Registered!";
                        } else {
                            $account->create();
                            $message['type'] = "success";
                         }
                    } else {
                        $message = 'Invalid email!, Please enter a valid Email';
                    }

header('Content-Type: application/json');
$response = ['message' => $message];
echo json_encode($response);
 // echo json_encode($message);
//echo $message;

这是我的AJAX

$.ajax({
            type: 'POST',
            url: 'register.php',
            dataType: 'json',
            data: formData,
            success: function (data) {
                $("#json").html(data["message"]);
                //response = response.slice(0, -1);
                //response = JSON.parse(response);
                //var json = JSON.parse(response);
                //var resdata = response;
                //var json = $.parseJSON(response);
                //if (resdata) {

                    //alert(resdata['success']);
                    //alert(json['success']);
                    // $("#register-form").addClass("remove-form");
                    // $("#register_container").addClass("register-container-active");
                    // $("#register_title").html("Register was Successful");
                    // $(".reg-notification").addClass("show-reg-notification");
                //}else if (resdata['email']) {
                    //alert(resdata['email']);
                //}
                    //alert(json['email']);
                    //$("#msg").html(json.email);
                //}
                console.log(response);
            },
            error:function(error){
                console.log(error);
            }
        });

您可以看到我注释的所有代码都是失败的代码,我希望在我的#json ID中显示来自PHP的消息。

我想做的是通过AJAX将PHP的“成功”编码从HTML编码为HTML,如果用户注册成功,如果用户存在,也将“电子邮件”错误排除。

我不知道在AJAX中使用什么条件进行测试或如何进行测试,我知道这很简单。

但是当我继续看着:(

2 个答案:

答案 0 :(得分:0)

   $.ajax({
                type: 'POST',
                url: 'register.php',
                dataType: 'json',
                data: formData,
                success: function (data) {
                    console.log(data.message.email);//that will print email already registered 


                var result=data.message.email;
                if(result=="success"){
                   $("#json").empty();//incase it has previous data
                   $("#json").append(result);//that will append data in your div

}
else{

    $("#json").empty();//incase it has previous data
                   $("#json").append(result);//that will append data in your div
}

                },
                error:function(error){
                    console.log(error);
                }
            });

答案 1 :(得分:0)

您需要先修改您的php响应。

$response = [];
if (strlen($password) >= 8 && strlen($password) <= 60) {
    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $account->addUser($username, $password, $email);
        if ($account->userExist()) {
            $response['type'] ="error";
            $response['msg'] = "Email Address Is Already Registered!";
        } else {
            $account->create();
            $response['type'] = "success";
            $response['msg']="You are signed in successfully";
        }
    } else {
        $response['type'] ="error";
        $response['msg'] = 'Invalid email!, Please enter a valid Email';
    }
    echo json_encode($response);
}

//输出

{"type":"success","msg":"You are signed in successfully"}

// ajax

$.ajax({
            type: 'POST',
            url: 'register.php',
            dataType: 'json',
            data: formData,
            success: function (data) {
                $("#json").html(data["msg"]);

                //get the response type simply as data['type'] this will give you success or error

                console.log(data);
            },
            error:function(error){
                console.log(error);
            }
        });