现场的用户名查找与AJAX / jQuery的 [英] Live username lookup with AJAX/Jquery
本文介绍了现场的用户名查找与AJAX / jQuery的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想有一个JavaScript函数像这样的:
I want to have a javascript function such as this:
function isUsernameAvailable(username)
{
//Code to do an AJAX request and return true/false if
// the username given is available or not
}
怎么可以这样使用jQuery或xajax的完成?
How can this be accomplished using Jquery or Xajax?
推荐答案
在使用AJAX的是,它是异步的重大胜利。你问了一个同步函数调用。这是可以做到的,但它可能会锁定在浏览器而这是等待服务器
The big win when using AJAX is that it is asynchronous. You're asking for a synchronous function call. This can be done, but it might lock up the browser while it is waiting for the server.
使用jQuery的:
function isUsernameAvailable(username) {
var available;
$.ajax({
url: "checkusername.php",
data: {name: username},
async: false, // this makes the ajax-call blocking
dataType: 'json',
success: function (response) {
available = response.available;
}
});
return available;
}
您PHP的code应再检查数据库,并返回
Your php-code should then check the database, and return
{available: true}
如果名称是确定的。
这是说,你应该这样做异步的。像这样:
That said, you should probably do this asynchronously. Like so:
function checkUsernameAvailability(username) {
$.getJSON("checkusername.php", {name: username}, function (response) {
if (!response.available) {
alert("Sorry, but that username isn't available.");
}
});
}
这篇关于现场的用户名查找与AJAX / jQuery的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文