[英]Username availability check using AJAX
I'm currently trying to develop a small website in PHP to test my skills. 我目前正在尝试用PHP开发一个小型网站来测试我的技能。 However I found myself stuck when I decided to implement a live username availability check for the sign up process, as my JavaScript knowledge is somewhat basic.
但是,当我决定为注册过程实施实时用户名可用性检查时,发现自己陷入了困境,因为我的JavaScript知识有些基础。
Right now when I put some name in the username field, I only get the loading image and nothing else. 现在,当我在用户名字段中输入一些名称时,我只会得到正在加载的图像,而没有别的。 This is what I have done:
这是我所做的:
My login.php page stored in the /views folder: 我的login.php页面存储在/ views文件夹中:
<section>
<div>
<form action="?action=login" method="post">
<input type="text" placeholder="username" name="username" id="username" onkeypress ="check()">
<span id="usernameStatus"></span>
</form>
</div>
</section>
My js file stored in /views/js: 我的js文件存储在/ views / js中:
function check () {
var status = document.getElementById('usernameStatus');
var u = document.getElementById('username').value;
if(u != ""){
status.innerHTML = '<img src="views/img/wait.gif" alt="" height="20" />';
var hr = new XMLHttpRequest();
hr.open("POST", "../login.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
status.innerHTML = hr.responseText;
}
}
var v = "checkName="+u;
hr.send(v);
}
}
And finally the loginController.php stored in /controllers: 最后,loginController.php存储在/ controllers中:
public function run() {
if(!empty($_POST["checkName"])){
$name= htmlentities($_POST["checkName"]);
if(Db::getInstance()->username_ok($name)){
echo ("<strong>" . $name . "</strong> unavailable");
}
else{
echo ("<strong>" . $name . "</strong> available");
}
}
require_once('views/login.php');
}
Could someone explain me what have I done wrong? 有人可以解释一下我做错了什么吗? Thanks!
谢谢!
这是一个可以帮助您的教程 ,它是一个使用PHP和jquery的实时用户名检查器。
I think the problem is with filenames. 我认为问题出在文件名上。
From your question, I guess the file structure is 从您的问题,我想文件结构是
root
|-- controllers
| `-- loginController.php
`-- views
`-- js
`-- script.js
In your JavaScript code which is in the file views/js/scriptname.js
, 在您的JavaScript代码(位于
views/js/scriptname.js
文件中)中,
hr.open("POST", "../login.php", true);
request is sent to the file login.php
. 请求发送到文件
login.php
。
But, as you have mentioned, the path to your server side php script is /controllers/loginController.php
. 但是,正如您已经提到的,服务器端php脚本的路径是
/controllers/loginController.php
。
According to me, the JavaScript code should be as following: 据我说,JavaScript代码应如下所示:
hr.open("POST", "controllers/loginController.php", true);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.