在JavaScript回调函数设置局部变量 [英] Setting local variable in a JavaScript callback function

查看:465
本文介绍了在JavaScript回调函数设置局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是比较新的JavaScript和我想我知道回调函数是如何工作的,但经过了几个在网上搜索的时间我还是不明白,为什么我的code是行不通的。

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 is not working.

我想提出一个AJAX请求返回一个字符串数组。我试图设置该数组到一个局部变量,但它似乎失去了它的价值,一旦回调函数被执行。

I am making an AJAX request which returns a string array. I'm trying to set this array to a local variable, but it seems to lose it's value as soon as the callback function is executed.

    var array;

    $.ajax({
        type: 'GET',
        url: 'include/load_array.php',
        dataType: 'json',
        success: function(data){
            array = data;
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert("Error loading the data");
        }
    });

    console.debug(array);

在控制台中,阵列显示为未定义。谁能给我解释一下这是为什么不被设置以及它如何可以在回调函数中设置一个局部变量。

In the console, array appears as undefined. Can anyone explain to me why this is not being set and how it is possible to set a local variable in a callback function.

推荐答案

这里的问题是,的console.log 同步执行,而Ajax调用异步执行。因此,它运行在回调完成之前,所以仍然把阵列未定义,因为成功尚未运行。为了使这项工作,你需要延迟的console.log 调用,直到成功后完成。

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

这篇关于在JavaScript回调函数设置局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆