如何在下一次 AJAX 调用中访问从一个 AJAX 调用返回的变量


how to access returned variable from one ajax call in next ajax call

我想在另一个 ajax 调用中访问一个 ajax 调用返回的变量

,并希望连续重复第二个 ajax 调用。 我的代码如下,代码注释中提到了所需的变量。

<script type="text/javascript" language="javascript">
    $( document ).ready(function() {
        $.ajax({
        url  : "functions.php?id=enter_game&name=<?php echo $name; ?>",
        type : "GET",
        //dataType : 'json',
        success: function(result){
            if(result){
                $("#game_status").html(result["game"]);
                var limit = Object.keys(result).length - 4;
                for(var x = 1; x <= limit ; x++)
                {
                    $("#users").append('<li>'+result[x]["name"]+'</li>');    
                    //$("#users").append('<li>abd</li>');
                }
                // I want to access these variables in next ajax call
                var user_id = result["current_user_id"];
                var word_id = result["word_id"];
                }
                }
                });
                // start updating continuously
                var timer, delay = 1000; // time in milli seconds
                    timer = setInterval(function(){
                        $.ajax({
                          type    : 'GET',
                          // the variables from previous ajax call result should be avaialable here
                          // and only this ajax call should be made upon delay time.
                          // previous ajax call should not be made more than once.
                          url     : 'functions.php?user_id='+user_id+'&word_id='+word_id,
                          //dataType: 'json',
                          success : function(data){
                                      if(data){
                                        $("#game_status").html(Math.floor((Math.random() * 10) + 1));
                                      }
                                    },
                            error: function( xhr, status, errorThrown ) {
                            alert( "Sorry, there was a problem! Error: " + errorThrown + ", Status: " + status + ", xhr: ," + xhr);
                            console.log( "Error: " + errorThrown );
                            console.log( "Status: " + status );
                            console.dir( xhr );
                            }
                        });
                    }, delay);
                });
</script>

任何帮助将不胜感激。

尝试以下代码。 声明变量 在 side 函数。 在此处阅读有关 Java 脚本中的变量作用域的更多信息

 <script type="text/javascript" language="javascript">
 var user_id;
 var word_id;
$( document ).ready(function() {
    $.ajax({
    url  : "functions.php?id=enter_game&name=<?php echo $name; ?>",
    type : "GET",
    //dataType : 'json',
    success: function(result){
        if(result){
            $("#game_status").html(result["game"]);
            var limit = Object.keys(result).length - 4;
            for(var x = 1; x <= limit ; x++)
            {
                $("#users").append('<li>'+result[x]["name"]+'</li>');    
                //$("#users").append('<li>abd</li>');
            }
            // I want to access these variables in next ajax call
            user_id = result["current_user_id"];
            word_id = result["word_id"];
            }
            }
            });
            // start updating continuously
            var timer, delay = 1000; // time in milli seconds
                timer = setInterval(function(){
                    $.ajax({
                      type    : 'GET',
                      // the variables from previous ajax call result should be avaialable here
                      // and only this ajax call should be made upon delay time.
                      // previous ajax call should not be made more than once.
                      url     : 'functions.php?user_id='+user_id+'&word_id='+word_id,
                      //dataType: 'json',
                      success : function(data){
                                  if(data){
                                    $("#game_status").html(Math.floor((Math.random() * 10) + 1));
                                  }
                                },
                        error: function( xhr, status, errorThrown ) {
                        alert( "Sorry, there was a problem! Error: " + errorThrown + ", Status: " + status + ", xhr: ," + xhr);
                        console.log( "Error: " + errorThrown );
                        console.log( "Status: " + status );
                        console.dir( xhr );
                        }
                    });
                }, delay);
            });

定义第一个 ajax 函数之外的变量。

 $( document ).ready(function() {
   //define them here first
   var user_id = '';
   var word_id = '';
    $.ajax({
    url  : "functions.php?id=enter_game&name=<?php echo $name; ?>",
    type : "GET",
    //dataType : 'json',
    success: function(result){
        if(result){
            $("#game_status").html(result["game"]);
            var limit = Object.keys(result).length - 4;
            for(var x = 1; x <= limit ; x++)
            {
                $("#users").append('<li>'+result[x]["name"]+'</li>');    
                //$("#users").append('<li>abd</li>');
            }
            //then set them here
            user_id = result["current_user_id"];
            word_id = result["word_id"];
            }
            }
            });
            // start updating continuously
            var timer, delay = 1000; // time in milli seconds
                timer = setInterval(function(){
                    $.ajax({
                      type    : 'GET',
                      // should be accessible from here
                      url     : 'functions.php?user_id='+user_id+'&word_id='+word_id,
                      //dataType: 'json',
                      success : function(data){
                                  if(data){
                                    $("#game_status").html(Math.floor((Math.random() * 10) + 1));
                                  }
                                },
                        error: function( xhr, status, errorThrown ) {
                        alert( "Sorry, there was a problem! Error: " + errorThrown + ", Status: " + status + ", xhr: ," + xhr);
                        console.log( "Error: " + errorThrown );
                        console.log( "Status: " + status );
                        console.dir( xhr );
                        }
                    });
                }, delay);
        });
});

在函数中设置第二个 ajax 函数,并在获得第一个 ajax 调用的响应后调用它

$(document).ready(function() {
  $.ajax({
    url: "functions.php?id=enter_game&name=<?php echo $name; ?>",
    type: "GET",
    //dataType : 'json',
    success: function(result) {
      if (result) {
        $("#game_status").html(result["game"]);
        var limit = Object.keys(result).length - 4;
        for (var x = 1; x <= limit; x++) {
          $("#users").append('<li>' + result[x]["name"] + '</li>');
          //$("#users").append('<li>abd</li>');
        }
        // I want to access these variables in next ajax call
        var user_id = result["current_user_id"];
        var word_id = result["word_id"];
        aftrAjax(user_id, word_id);
      }
    }
  });
  function aftrAjax(userid, wordid) {
    var timer, delay = 1000; // time in milli seconds
    timer = setInterval(function() {
      $.ajax({
        type: 'GET',
        // the variables from previous ajax call result should be avaialable here
        // and only this ajax call should be made upon delay time.
        // previous ajax call should not be made more than once.
        url: 'functions.php?user_id=' + user_id + '&word_id=' + word_id,
        //dataType: 'json',
        success: function(data) {
          if (data) {
            $("#game_status").html(Math.floor((Math.random() * 10) + 1));
          }
        },
        error: function(xhr, status, errorThrown) {
          alert("Sorry, there was a problem! Error: " + errorThrown + ", Status: " + status + ", xhr: ," + xhr);
          console.log("Error: " + errorThrown);
          console.log("Status: " + status);
          console.dir(xhr);
        }
      });
    }, delay);
  }
});

使用 jQuery.Deferred() 的更干净、更好的方法

下面的演示与其说是编辑代码,不如说是演示。因此,请随时根据您的情况进行调整。

$demo = $("#demo");  // remove - for demo only
var ajax1 = function() {
    $demo.append("Begin ajax call 1<br/>"); // remove - for demo only
    var dfd = $.Deferred();
    $.ajax({
        url: "/echo/xml/",
        //url: "functions.php?id=enter_game&name=<?php echo $name; ?>",
        type: "GET"
    }).done(function(result) {
        $demo.append("Ajax call 1 complete<br/>"); // remove - for demo only
        //your code...
        //............
        //............
        dfd.resolve(result);
    });
    return dfd.promise();
};
var ajax2 = function() {
    $.when(ajax1()).done(function(result) {
        // the variables from previous ajax call result are avaialable here
        //var user_id = result["current_user_id"];
        //var word_id = result["word_id"];
        $demo.append("Begin ajax call 2<br/>"); // remove - for demo only
        var times = 1;
        var repeatAjax = function() {
            if (times > 10) return; // remove - for demo only
            $demo.append("Ajax call 2 called " + times + " time(s)<br/>"); // remove - for demo only
            $.ajax({
                type: 'GET',
                url: "/echo/xml/", //['functions.php?user_id=', user_id, '&word_id=', word_id].join(""),
            }).done(function() {
                //your code...
                //............
                //............
                $demo.append("Ajax call 2 complete<br/>"); // remove - for demo only
                times++; // remove - for demo only
                //optional - you may want to subtract the approximate response time from 1000, so, you'd actually achieve close to 1000ms :)
                setTimeout(repeatAjax, 1000);
            });
        };
       repeatAjax();
    });
};
//Start the function
ajax2();