douyudouchao6779
2015-03-14 15:27
浏览 70
已采纳

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

I want to access returned variable from one ajax call in another ajax call and want to repeat the second ajax call continuously. my code is below, and the required variables are mentioned in code comments.

<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>

Any help would be much appreciated.

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • duanquan1207 2015-03-14 15:33
    已采纳

    try below code . declare variables out side function. read more about variable scope in java script here

     <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);
                });
    

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • douya1938 2015-03-14 15:33

    Define you variables outside of the first ajax function.

     $( 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);
            });
    });
    
    评论
    解决 无用
    打赏 举报
  • doushi1912 2015-03-14 15:35

    Set the second ajax function inside a function and call it after getting the response from first ajax call

    $(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);
      }
    });

    </div>
    
    评论
    解决 无用
    打赏 举报
  • dongyou7739 2015-03-14 16:49

    A cleaner and better way using jQuery.Deferred()

    The below is more of a demo than editing your code. So, feel free to adapt this to your situation.

    $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();
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题