2011-03-03 67 views
0

我敢肯定這是一件非常簡單的事情,但當我被困在這些東西時,我就是這麼一個小孩......已經過了2個小時,我討厭這個時候發生了什麼:(jQuery返回未定義POST調用

這是爲什麼返回undefined?

function userExists(user) { 
$.post("misc/user_exists.php", {user: user}, 
     function(result) { 
      return '' + result + ''; 
     }); 
}); 

PHP文件將返回用戶名完全正常,因爲我看到它在從螢火蟲的反應。但後來這個功能是沒用的,當我做警示在調用它之後,它總是未定義的,是否返回字符串,布爾值等。

謝謝!

+0

是'result'不確定?或者'userExists(user)'的返回值未定義? – 2011-03-03 14:16:07

+0

Try:console.log(result); Firebug說什麼? – 2011-03-03 14:17:40

+0

userExists(用戶)的結果。結果是用戶名存在的時候。 – luqita 2011-03-03 14:18:38

回答

6

$.post請求是異步的,所以當你運行return '' + result + '';它實際上沒有將數據返回到任何地方。相反,從AJAX成功函數中觸發一個不同的事件。

0

問題是返回將僅影響post方法中的ajax.sucess回調。試試這個:

function userExists(user, callback) //because this can be async, you need a callback... 
{ 
    $.post("misc/user_exists.php", {user: user}, 
    function(result) 
    { 
     if(callback) 
      callback(result) 
     return '' + result + ''; 
    }); 
}; 
userExists('someUser', function(result) 
{ 
    alert('' + result + '') 
}); 

或者,你可以確保呼叫不是異步:

function userExists(user) //because this can be async, you need a callback... 
{ 
    var res; 
    $.post("misc/user_exists.php", {user: user}, 
    function(result) 
    { 
     res = result; 
    }); 
    return res; 
}; 
$.ajax({async:false}); 
alert('' + userExists('someUser'+ '');  
-2

你可以這樣做

function userExists(user) { 
    var username = ''; 
$.post("misc/user_exists.php", {user: user}, 
     function(result) { 

      username = result ; 
     }); 
    return username; 
}); 
+0

而不是未定義,則您將返回''。該調用是異步的。 – epascarello 2011-03-03 15:16:27