2010-10-07 64 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