2010-10-07 62 views
8

我写了一个函数,它必须检查用户名是否已被使用。现在,当我从另一个函数调用函数并提醒它返回值时:返回来自Jquery AJAX调用的响应

 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'); 
     } 
    }); 
    }

我在做什么错?

回答

10

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);  
    }, 

该方法激发发送到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 
} 

编辑:

按照该OP的评论,你需要改变你的AJAX调用是同步的,而不是异步(我从没做过同步调用这样的自己,所以这是未经测试):

var ajaxResponse; 

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

return ajaxResponse; 

全部API上市here

+0

谢谢你的回答,我明白了。但它并没有解决我的问题。让我解释我想要进一步的一点。我从另一个函数中触发checkusernameavailable函数,当我的表单提交时触发它。所以我正在做的是: if(!checkusernameavailable(username_box.val())){ return false; //不要提交表格 //并使一些框变红,取消隐藏多语言错误消息(其中 - btw--表示我无法直接将响应插入到我的html中...)} – 2010-10-08 11:21:38

+0

@ user468893 - 请参阅我的编辑。您需要使您的Async AJAX调用同步。 – GenericTypeTea 2010-10-08 11:58:43

+0

它已经是,但这不是诀窍:)返回值做了魔术。谢谢! – 2010-10-08 12:10:34