duanmengmiezen8855
duanmengmiezen8855
2014-04-29 22:38

如何使用AJAX执行MYSQLI查询(预处理语句)

  • php
  • ajax
  • jquery

So I have this (prepared statement) mysqli query in PHP (partial code):

#New DB connection
@ $mysqli = new mysqli ('localhost', 'user', 'password', 'database');

#Check DB connection, print error upon failure
if (mysqli_connect_errno()) {
    printf("<p>Connect failed.</p> <p>Error: \"%s\"</p>
", mysqli_connect_error());
    exit();
} #if

#Check if userName already exists
$query = "SELECT * FROM users WHERE userName = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("s", $registerUserName);
$stmt->execute();
$stmt->store_result();
$num_results = $stmt->num_rows;
if ($num_results) {
    echo "<p>This user already exists. Please click your back button.</p>";
    exit;
}; #if

And I would like to execute this through Javascript/AJAX on an onblur event:

function checkForUser(str) {
  var xmlhttp;    
  if (str=="") {
    return;
  }
  if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  }
  else{// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
      document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
  xmlhttp.open(???,true); // not sure what goes here or if I should even use this method
  xmlhttp.send();
}

So is this possible? and how? I found some tutorials but they involve using jquery. Can I do it without jquery?

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答

为你推荐