2011-05-12 89 views
0

我需要從GET請求中獲取一個變量並在函數內部使用它。它不工作。這裏是我的代碼:從jQuery GET請求獲取變量

function chooseChosenOne() { 

     $.get("generate.php", function(data) { 
      var chosenOne = targetLocation[data.randomNumber]; 
     }, "json"); 

     alert(chosenOne); 

     } 

我該如何解決這個問題?如何在GET請求中使用該函數之外的變量「chosenOne」?

回答

0

您必須使用jQuery插件getURLParam

value = $.getURLParam("paramName"); 
0

在你打電話alert(chosenOne);時,Ajax回調尚未執行。 Ajax是異步。函數chooseChosenOne不會等到Ajax調用完成,它會立即返回。

只能在回調的工作返回值:

function chooseChosenOne() { 
    $.get("generate.php", function(data) { 
     var chosenOne = targetLocation[data.randomNumber]; 
     alert(chosenOne); 
    }, "json"); 
} 

所以,你所要做的就是讓你的函數接受它,即會叫的值可用回調:

function chooseChosenOne(callback) { 
    $.get("generate.php", function(data) { 
     callback(targetLocation[data.randomNumber]); 
    }, "json"); 
} 

chooseChosenOne(function(theOne) { 
    // now do stuff with theOne here 
}); 

參見:

0

「chosenOne」只存在回調函數裏面,你的代碼將達到警報()回調甚至運行之前...

function chooseChosenOne() {   
    $.get("generate.php", function(data) {    
       doSomethingWithChosenOne(targetLocation[data.randomNumber]); 
       }, "json"); 
} 

function doSomethingWithChosenOne(v){ 
    alert(v); 
}