<div>标记没有显示Ajax的JSON响应

时间:2015-12-04 12:29:45

标签: javascript php jquery json ajax

我做了一个简单的登录表单,我试图通过AJAX调用验证。它运作成功。但问题是,当我输入正确的电子邮件或密码时,它会刷新整个页面,而不是显示JSON成功错误,以div显示,错误的电子邮件/密码也是如此。请提出任何建议!!

代码

<script>
 $(document).ready(function() {
 $('#login_submit').click(function(){
 var  email = $("#email").val(),
 password = $("#password").val();
  var proceed = true;
  if(proceed){
 post_data= { 'Email': email, 'Password': password};
  $.post('login_index.php', post_data, function(response){
  //load json data from server and output message
   if(response.type == 'error')
   {
     output=$('.alert-error').html(response.text);
    }else{
    output=$('.alert-success').html(response.text);
   }
   $("#error").hide().html(output).slideDown();
                    }, 'json');
                }
           });
          });
    </script>

<div class="alert-error"></div>
<div class="alert-success"></div>
<div class="login">
    <form method="post" action="">
        <input type="email" name="email" id="email" placeholder="email" >
        <input type="password" name="password" id="password" placeholder="password">
        <input type="submit" name="login_submit" id="login_submit" value="login">
    </form>
</div>

    <?php
include "db/db.php";
session_start();
if($_POST){
    if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
 $output = json_encode(
            array(
                'type'=>'error',
                'text' => 'Request must come from Ajax'
            ));

        die($output);
    }
if(isset($_POST['Email']) && isset($_POST['Password']))
{
$email=filter_var($_POST["Email"], FILTER_SANITIZE_STRING);
$pwd=filter_var($_POST["Password"], FILTER_SANITIZE_STRING);
$query=mysqli_query($con,"select * from customers where email='$email' and password='$pwd'");
    $count=mysqli_num_rows($query);
    $row=mysqli_fetch_array($query,MYSQLI_ASSOC);
    if($row)
    {
       $_SESSION['login_email']=$row['email'];
        $output = json_encode(array('type'=>'message', 'text' => 'Hi '.$email .' You are successfully login'));
        die($output);

     }
    else{
        $output = json_encode(array('type'=>'error', 'text' => 'Could not login! Please check your email password.'));
        die($output);
    }
}

}

2 个答案:

答案 0 :(得分:3)

使用form阻止submite.preventDefault()按钮的默认操作,否则会发布form并发生页面刷新。

$('#login_submit').click(function(e){
     e.preventDefault(); //e is the event captured here
     //rest of the code
});

答案 1 :(得分:1)

您可以直接使用return false,这将阻止默认操作以及传播事件。

YEAR