2015-02-11 60 views
0

我試圖使用jQuery validate插件來檢查可用的名稱。 它對php文件發佈請求並獲得響應0或1.如何將jquery post結果傳遞給另一個函數

問題是我無法將結果傳遞給主函數。 請參閱下面

jQuery.validator.addMethod("avaible", function(value, element) { 

    $.post("/validate.php", { 
     friendly_url: value, 
     element:element.id 
    }, function(result) { 
     console.log(result) 
    }); 

    //How to pass result here??? 
    console.log(result) 
}, ""); 
+1

'myOtherFunction(result)' – adeneo 2015-02-11 00:37:18

+2

歡迎來到異步JavaScript的世界。 – 2015-02-11 00:42:26

+0

因爲'console.log()'是一個函數,所以你實際上已經用'console.log(result)'來完成它了。 (即另一個函數,但不能返回到調用該函數的函數開始) – developerwjk 2015-02-11 00:45:07

回答

0

所以人們已經說過,它是異步的,它是myOtherFuntion :-)

我只是結合這些評論到某種形式的答案我對你的代碼:

function myOtherFunction(result) { 
// here you wrote whatever you want to do with the response result 
//even if you want to alert or console.log 
    alert(result); 
    console.log(result); 
} 

jQuery.validator.addMethod("avaible", function(value, element) { 

    $.post("/validate.php", { 
     friendly_url: value, 
     element:element.id 
    }, function(result) { 
     myOtherFunction(result); 
    }); 

    //How to pass result here??? 

    //there is no way to get result here 
    //when you are here result does not exist yet 
}, ""); 
0

由於Javascript的異步特性,console.log(result)將不起作用,因爲服務器尚未返回結果數據。

jQuery.validator.addMethod("avaible", function(value, element) { 

$.post("/validate.php", { 
    friendly_url: value, 
    element:element.id 
}, function(result) { 
    console.log(result); 
    doSomethingWithResult(result); 
}); 

function doSomethingWithResult(result) { 
    //do some stuff with the result here 
} 
}, ""); 

以上將允許您將結果傳遞給另一個函數,這將讓你實現訪問和處理結果的工作一旦從服務器返回。

相關問題