Skip to main content
 首页 » 编程设计

javascript之ajax之验证数据库中是否已存在行

2026年07月28日9jiqing9006

我有一个简单的表单,用于将电子邮件地址提交到数据库。我想首先使用 javascript 和 AJAX 检查该电子邮件地址是否已存在于表中。无论该行是否已存在于数据库中,我使用的代码始终返回 true。有什么提示吗?

JS代码

<script>  
$('form').submit(function(e)  
{ 
  alert('submit intercepted'); 
  e.preventDefault(e); 
  var u = $('#email').val(); 
  $.ajax({ 
      url: './test2.php', 
      type: 'POST', 
      data: u, 
      success: function (response) { 
      //get response from your php page (what you echo or print) 
        $('#status').append('<p>The email is ok to use and the row has been inserted </p><p>' + response); 
        console.log('Submitted'); 
      }, 
      error: function(jqXHR, textStatus, errorThrown) { 
        console.log(textStatus, errorThrown); 
        alert('Email exists'); 
      } 
    }); 
}); 
</script> 

HTML 代码

<form id="form" action="./test2.php" method="post">  
    E-mail: <input type="email" name="email" id="email" required><br> 
    <span id="status">   </span> 
    <input type="submit" id="btnsub"> 
  </form> 

PHP 代码

if(isset($email)) { 
 
  $sql_email_check = $conn->query("SELECT Email FROM test WHERE Email='$email' LIMIT 1") ; 
 
  $email_check = $sql_email_check->num_rows; 
 
  if ($email_check < 1) { 
 
    //return "Available"; 
    return true;    
    //header('Location: /test.php'); 
    exit(); 
 
  }  
  else  
  { 
    //return "Unavailable"; 
    return false; 
    //header('Location: /test.php'); 
    exit();  
 
  } 
} 

请您参考如下方法:

所以基本上问题是将答案从 php 代码返回到 ajax 函数。由于某种原因,返回值没有按照预期正确解释(无论如何,根据我的理解)

PHP 代码

if(isset($email)) {     
  $sql_email_check = $conn->query("SELECT Email FROM test WHERE Email='$email' LIMIT 1") ;      
  $email_check = $sql_email_check->num_rows;     
 
  if ($email_check == 0) { 
    echo 'true';   
    return;  
    }  
  else  
  { 
    echo 'false'; 
    return;     
  } 
} 

JS 代码

<script>  
$('form').submit(function(e)  
{ 
  alert('submit intercepted'); 
  e.preventDefault(e); 
  var u = { 'email': $('#email').val() }; 
  $.ajax({ 
      url: 'test2.php', 
      type: 'POST', 
      //dataType: 'string', 
      data: u, 
      success: function (response) { 
        //get response from your php page (what you echo or print) 
        console.log(response); 
 
        if (response === 'true') { 
          $('#status').append('<p>The email is ok to use and the row has been inserted </p><p>' + response); 
 
        } else { 
          console.log('Email does exist '); 
 
        } 
      }, 
      error: function(jqXHR, textStatus, errorThrown) { 
        console.log(textStatus, errorThrown); 
 
      } 
    }); 
}); 
</script>