从Jquery AJAX调用返回响应

Jor*_*ris 10 javascript ajax jquery

我写了一个函数,它必须检查是否已经使用了用户名.现在当我从另一个函数调用该函数时,并提示它的返回值:

 alert(checkusernameavailable('justausername')); 

它说"未定义".我搜索过高低,但找不到我做错了什么.我想它应该只返回check.php中的php-echo,但事实并非如此.这是我写的函数:

var checkusernameavailable = function(value)  {
    $.ajax({
      url: "check.php",
      type: "POST",
      async: false,
      cache: false,
      data: "username=" + value + "",

      success: function(response) {
        alert(response);
        return response;        
      },
      error: function() {
        alert('ajax error');
      }
    });
  } 

我究竟做错了什么?

djd*_*d87 12

AJAX调用是异步的,这意味着它们只在操作完成后返回数据.即方法checkusernameavailable永远不会返回任何信息(除非你在该方法本身内告诉它).您需要执行以下操作:

// Just fire and forget the method
checkusernameavailable("userName");

// Change the success function to do any display you require
success: function(response) {
    alert(response);
    $("#SomeDiv").html(response);     
  },
Run Code Online (Sandbox Code Playgroud)

该方法触发发布到check.php的AJAX异步方法.收到响应后,您可以在与成功回调相关的函数中处理该响应$.ajax.您也可以直接为该成功回调指定一个函数:

// Change success to point to a function name
success: foo

// Create a function to handle the response
function foo(response)
{
   // Do something with response
}
Run Code Online (Sandbox Code Playgroud)

编辑:

根据OP的评论,你需要将你的AJAX调用改为同步,而不是异步(我自己从未做过这样的同步调用,所以这是未经测试的):

var ajaxResponse;

$.ajax({
    async: false, 
    success : function (response)
              {
                  ajaxResponse = response;
              },
    // other properties
});

return ajaxResponse;
Run Code Online (Sandbox Code Playgroud)

这里有完整的API列表.