在继续之前,
SELECt * FROM 'users' WHERe 'username' = '.$_POST['username'];只是向SQL注入提问。我建议您使用PHP数据对象-http://php.net/manual/zh/book.pdo.php。
因此,据我了解,我也必须通过$ .ajax传递POST值,对吗? 如果是,我将如何通过validation.php文件访问它们?
因为这是一个简单的请求,所以建议您使用JQuery的method
$.post()。这是基于您要执行的操作的示例。
$.post('validation.php',{username: $('#username').val()}, function(data){ if(data.exists){ //tell user that the username already exists }else{ //username doesn't exist, do what you need to do } }, 'JSON');jQuery的post方法采用4个参数
$.post(url, data, callback,datatype)。在上面的示例中,我们将用户名与
$('#username').val()一起发布,validation.php并期望得到
JSON响应。请求完成后,回调函数将作为
data请求的响应执行。因为我们指定该响应为
JSON,所以我们可以像访问javascript中的本机对象一样访问它。现在让我们转到validation.php
就像我上面所说的,我建议您将PDO用于数据库驱动程序。因此,在此示例中,我将向您展示其基本用法。
//set the headers to be a json stringheader('content-type: text/json');//no need to continue if there is no value in the POST usernameif(!isset($_POST['username'])) exit;//initialize our PDO class. You will need to replace your database credentials respectively$db = new PDO('mysql:host=DATAbase_HOST;dbname=DATAbase_NAME','DATAbase_USERNAME','DATAbase_PASSWORD',array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));//prepare our query.$query = $db->prepare('SELECT * FROM users WHERe username = :name');//let PDO bind the username into the query, and prevent any SQL injection attempts.$query->bindParam(':name', $_POST['username']);//execute the query$query->execute();//return the json object containing the result of if the username exists or not. The $.post in our jquery will access it.echo json_enpre(array('exists' => $query->rowCount() > 0));现在回顾一下,我们的jQuery脚本将发布到
validation.php从数据库中选择用户名的位置。它将返回一个
JSON对象,该对象的键为
exists布尔值,指示用户名是否已存在于数据库中。通过jQuery完成请求后,您可以根据查询结果执行所需的操作。我希望这是一个详尽的解释,并引导您完成您希望完成的工作。



