Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/78.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
Javascript jQuery.getJSON始终返回空对象_Javascript_Jquery_Json_Undefined_Getjson - Fatal编程技术网

Javascript jQuery.getJSON始终返回空对象

Javascript jQuery.getJSON始终返回空对象,javascript,jquery,json,undefined,getjson,Javascript,Jquery,Json,Undefined,Getjson,我一直在寻找一种从JSON文件中包含对象的方法,我找到了几页总结如何使用$.getJSON(),这里甚至有一些答案,但都不起作用。有人建议我这样做: var json; $.getJSON("dir/1.json", function(response){ json = response; }); var json = $.getJSON("dir/1.json"); 有些人这样建议: var json; $.getJSON("dir/1.json", function(resp

我一直在寻找一种从JSON文件中包含对象的方法,我找到了几页总结如何使用$.getJSON(),这里甚至有一些答案,但都不起作用。有人建议我这样做:

var json;

$.getJSON("dir/1.json", function(response){
    json = response;
});
var json = $.getJSON("dir/1.json");
有些人这样建议:

var json;

$.getJSON("dir/1.json", function(response){
    json = response;
});
var json = $.getJSON("dir/1.json");

这两种方法都不管用。当我尝试调用
json
的属性时,例如
json.title
,它只会给我一个错误,告诉我变量未定义。似乎没有其他人有这个问题,那么我做错了什么?

响应被推迟。在您读取变量时,响应可能尚未响应。尝试访问函数回调中的变量,就在
json=response之后

响应延迟。在您读取变量时,响应可能尚未响应。尝试访问函数回调中的变量,就在
json=response之后

尝试使用以下方法:

var json = $.getJSON( "dir/1.json" )
    .done(function( response ) {
        json = response;
        console.log( "json variable ready" );
    })
    .fail(function() {
        console.log( "error" );
    });
更新


$.getJSON()返回的响应对象实现promise接口,为其提供promise的所有属性、方法和行为。因此,在返回响应或启动done函数之前,json尚未就绪。

尝试使用以下方法:

var json = $.getJSON( "dir/1.json" )
    .done(function( response ) {
        json = response;
        console.log( "json variable ready" );
    })
    .fail(function() {
        console.log( "error" );
    });
更新


$.getJSON()返回的响应对象实现promise接口,为其提供promise的所有属性、方法和行为。因此,在返回响应或启动done函数之前,json尚未准备就绪。

您了解相对路径和绝对路径之间的区别吗?是的,并且文件是相对的。您了解相对路径和绝对路径之间的区别吗?是的,$.getJSON()返回的响应对象实现了
promise
接口,为它提供了
promise
的所有属性、方法和行为。因此,在返回响应或启动
done
函数之前,
json
还没有准备好。就这样做了。感谢您的建议$.getJSON()返回的响应对象实现了
promise
接口,为它提供了
promise
的所有属性、方法和行为。因此,在返回响应或启动
done
函数之前,
json
还没有准备好。就这样做了。谢谢你的建议