Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JSON javascript未定义变量问题_Javascript_Ajax_Json - Fatal编程技术网

JSON javascript未定义变量问题

JSON javascript未定义变量问题,javascript,ajax,json,Javascript,Ajax,Json,我发现了这个问题,但是我的解决方案不起作用。变量d0和d1将填充,但在代码创建并拼接阵列存储位置之后。因此,我得到一个错误,d0和d1未定义。有什么解决办法吗 Javascript: $(function () { $.get("/Map/GetJsonData", function (data) { storeLocations = []; var d0 = data[0].Delay; var

我发现了这个问题,但是我的解决方案不起作用。变量d0和d1将填充,但在代码创建并拼接阵列存储位置之后。因此,我得到一个错误,d0和d1未定义。有什么解决办法吗

Javascript:

    $(function () {


        $.get("/Map/GetJsonData", function (data) {
            storeLocations = [];
            var d0 = data[0].Delay;
            var d1 = data[1].Delay;


        });

        var storeLocations = new Array();
        storeLocations.splice(storeLocations.length, 0, d0);
        storeLocations.splice(storeLocations.length - 1, 0, d1);


}

AJAX是异步的,可以创建回调,也可以在AJAX回调中执行所需的操作:

$.get("/Map/GetJsonData", function (data) {
        storeLocations = [];
        var d0 = data[0].Delay;
        var d1 = data[1].Delay;

        var storeLocations = new Array();
        storeLocations.splice(storeLocations.length, 0, d0);
        storeLocations.splice(storeLocations.length - 1, 0, d1);
});

由于您是在$.get方法的回调函数中声明变量(d0和d1),因此这些变量是私有的,只能在声明它们的行之后在该函数中访问。因此,您应该将storeLocations代码移到回调函数中

 $(function () {


    var storeLocations = new Array();
    $.get("/Map/GetJsonData", function (data) {
        storeLocations = [];
        var d0 = data[0];
        var d1 = data[1];


        storeLocations.splice(storeLocations.length, 0, d0);
        storeLocations.splice(storeLocations.length - 1, 0, d1);

    });
});

在我的示例中,我在$.get方法的作用域之外声明了storeLocations,因此可以在jQuery document ready方法作用域内的任何位置(在声明它的行之后)访问它。

作用域不在外部函数中吗?