Live username lookup with AJAX/Jquery

好久不见. 提交于 2019-12-02 13:38:14

问题


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
}

How can this be accomplished using Jquery or Xajax?


回答1:


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.

Using 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

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


来源:https://stackoverflow.com/questions/577231/live-username-lookup-with-ajax-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!