【问题标题】:Getting variable from jQuery GET request从 jQuery GET 请求中获取变量
【发布时间】:2011-05-12 23:16:53
【问题描述】:

我需要从 GET 请求中获取一个变量并在函数中使用它。它不工作。这是我的代码:

function chooseChosenOne() {

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

         alert(chosenOne);

       }

我该如何解决这个问题?如何在 GET 请求中使用该函数之外的变量“chosenOne”?

【问题讨论】:

    标签: javascript jquery global-variables


    【解决方案1】:

    你必须使用jQuery插件getURLParam

    value = $.getURLParam("paramName");
    

    【讨论】:

      【解决方案2】:

      'chosenOne' 只存在于你的回调函数中,你的代码会在回调运行之前触发 alert()...

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

      【讨论】:

        【解决方案3】:

        在您调用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
        });
        

        另见:

        【讨论】:

          猜你喜欢
          • 2012-07-02
          • 1970-01-01
          • 1970-01-01
          • 2012-01-15
          • 1970-01-01
          • 2021-08-29
          • 2021-06-04
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多