Setting local variable in a JavaScript callback function

后端 未结 5 1876
余生分开走
余生分开走 2021-01-02 11:33

I\'m relatively new to JavaScript and I thought I knew how callback functions worked but after a couple of hours of searching the web I still do not understand why my code i

相关标签:
5条回答
  • 2021-01-02 11:56

    The first A in ajax is for Asynchronous, which means that by the time you are debugging the array, the result still hasn't been delivered. Array is undefined at the point of displaying it's value. You need to do the console.debug below array = data.

    0 讨论(0)
  • 2021-01-02 12:00

    The success function doesn't execute immediately, but only after the HTTP-response arrives. Therefore, array is still undefined at this point. If you want to perform operations on the HTTP-response data, do it from within the success function, or alternatively, define that operation inside of a function and then invoke that function from within the success callback.

    0 讨论(0)
  • 2021-01-02 12:04

    The problem here is that console.log executes synchronously while the ajax call executes asynchronously. Hence it runs before the callback completes so it still sees array as undefined because success hasn't run yet. In order to make this work you need to delay the console.log call until after success completes.

    $(document).ready(function() {
        var array;
    
        var runLog = function() {
          console.log(array); 
        };
    
        $.ajax({
          type: 'GET',
          url: 'include/load_array.php',
          dataType: 'json',
          success: function(data){
            array = data;
            runlog();
        }});
    });
    
    0 讨论(0)
  • 2021-01-02 12:09

    Try calling a function to set this variable after your success:

    var array;
    
    var goodToProceed = function(myArr) {
       console.debug(myArr);
    };
    
    $.ajax({
    type: 'GET',
    url: 'include/load_array.php',
    dataType: 'json',
    success: function(data){
        goodToProceed(data);
    },
    error: function(jqXHR, textStatus, errorThrown){
        alert("Error loading the data");
    }
    });
    
    0 讨论(0)
  • 2021-01-02 12:16

    AJAX is asynchronous. You are setting the array variable, but not until after that debug executes. Making an AJAX call sends a request but then continues on in the code. At some later point, the request returns and your success or error functions execute.

    0 讨论(0)
提交回复
热议问题