简体   繁体   English

使用AJAX / Jquery进行实时用户名查找

[英]Live username lookup with AJAX/Jquery

I want to have a javascript function such as this: 我想要一个像这样的javascript函数:

function isUsernameAvailable(username)
{
   //Code to do an AJAX request and return true/false if
  // the username given is available or not
}

How can this be accomplished using Jquery or Xajax? 如何使用Jquery或Xajax完成此操作?

The big win when using AJAX is that it is asynchronous. 使用AJAX的最大好处是它是异步的。 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. 可以这样做,但是它可能会在等待服务器时锁定浏览器。

Using jquery: 使用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;
}

Your php-code should then check the database, and return 然后,您的php代码应检查数据库,然后返回

{available: true}

if the name is ok. 如果名称可以。

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.");
        }
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM