我需要读取一个文件json以在.html之类的网页中使用,我正在尝试,但是我所有的代码都失败了。 我最后的代码就是它。
function getJson(file) {
var val;
val = $.getJSON( file, function() {
console.log( "success" );
});
return val;
}
然后我这样调用其他函数
function sourceVideo() {
var val=getJson('example.json')
alert(val.example);
}
但是不确定的还给我。
我现在尝试了这个:
var textfile;
var allText;
function readTextFile(file)
{ return new Promise(function(resolve, reject) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
allText = rawFile.responseText;
}
}
}
rawFile.send(null);
});
}
function init(){
readTextFile("config.json")
.then(function(allText){
alert(allText);
textfile=allText;
})
.catch(function(){
});
var json=JSON.parse(textfile);
alert(json.nameFile);
}
我一直以文本模式读取文件,并在json中解析后,但readTextFile中的警报起作用,读取了所有文件。 但是在init()中,allText是未定义的,因此JSON.parse无法工作。
非常感谢您的支持。