Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/477.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.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中的外部json文件_Javascript_Json - Fatal编程技术网

读取javascript中的外部json文件

读取javascript中的外部json文件,javascript,json,Javascript,Json,如何在javascript中读取外部json文件? 我已经使用了getjson、json.parse方法,但它不起作用 我的json文件名是“testquestions.json”。这应该可以: $.getJSON( "testquestions.json", function( data ) { console.log(data); }); 签出。您必须使用AJAX读取文件。您必须使用get请求来请求该文件 可以在suces块中调用函数。 使用原始javascript: if (win

如何在javascript中读取外部json文件? 我已经使用了getjson、json.parse方法,但它不起作用

我的json文件名是“testquestions.json”。

这应该可以:

$.getJSON( "testquestions.json", function( data ) {
  console.log(data);
});

签出。

您必须使用AJAX读取文件。您必须使用get请求来请求该文件

可以在suces块中调用函数。 使用原始javascript:

if (window.XMLHttpRequest)
{
 // AJAX IE7+, Chrome, Firefox, Safari, Opera
   xmlhttp=new XMLHttpRequest();
}else{
 //AJAX IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
   if (xmlhttp.readyState==4 && xmlhttp.status==200){
     //get the returned data
     document.getElementById("RESPONSE").innerHTML=xmlhttp.responseText;
   }
}
xmlhttp.open("GET",URI_TO_FILE,true);
xmlhttp.send();
}

要从路径读取JSON文件,请执行以下操作:

var configuartion=null;
$.getJSON("./resources/js/testquestions.json", function(data)
                      {
                        configuartion=data;
                      }
            );

使用configuation变量,您可以访问JavaScript中的JSON数据。

JavaScript本身没有读取文件的能力。这取决于主机环境是否为此提供API。您使用的主机环境是什么?Node.js?Windows脚本主机?网页中的脚本元素?你说的“文件”是指实际的文件吗?还是说HTTP资源?还是别的什么?如果您指的是HTTP资源,那么外部资源是什么意思?在运行JS的站点外部?在另一个站点上?这个问题几乎肯定也有重复的地方。“我已经使用了getjson,json.parse方法”-如何?你还没有提供一个@Quentin你确定吗?JavaScript本机读取文件的能力是。@DanFromGermany-
XMLHttpRequest
是某些主机环境提供的扩展。它不是JavaScript的本机部分。除非OP提到了jQuery方法并忘记标记jQuery(getJSON),谢谢Qentin-更新了答案@昆汀,除非OP不知道标记jQuery。在jQuery中提到getJSON点
var configuartion=null;
$.getJSON("./resources/js/testquestions.json", function(data)
                      {
                        configuartion=data;
                      }
            );