Javascript 如何使用json从java脚本中的文本文件检索数据
我用json_demo.text制作了一个文本,现在我正在尝试检索这个文本文件的数据Javascript 如何使用json从java脚本中的文本文件检索数据,javascript,html,json,ajax,Javascript,Html,Json,Ajax,我用json_demo.text制作了一个文本,现在我正在尝试检索这个文本文件的数据 { "name":"John", "age":31, "pets":[ { "animal":"dog", "name":"Fido" }, { "animal":"cat", "name":"Felix" }, { "animal":"hamster", "name":"Lightning" } ] }//**json_demo.
{
"name":"John",
"age":31,
"pets":[
{ "animal":"dog", "name":"Fido" },
{ "animal":"cat", "name":"Felix" },
{ "animal":"hamster", "name":"Lightning" }
]
}//**json_demo.txt**
您可以使用Ajax。例如: $.ajax({ url:“./json_demo.txt”, async:false, 成功:功能(数据){
将文件重命名为
.json
,并将其放置在与项目相同的文件夹中
现在,对文件发出一个Ajax请求,相对路径为URL.Like/file.json
$.ajax({
url : './file.json',
method : 'POST',
success : function(resp){
data = JSON.parse(resp.data);
console.log(data);
}
});
首先将其存储在变量中
var mydata =
{
"name":"John",
"age":31,
"pets":[
{ "animal":"dog", "name":"Fido" },
{ "animal":"cat", "name":"Felix" },
{ "animal":"hamster", "name":"Lightning" }
]
}//**json_demo.txt**
现在,您可以使用变量mydata在javascript中访问它:
alert('I love' + mydata.pets.animal);
使用AJAX:
<script type="text/javascript">
$.ajax({
type : 'GET',
dataType : 'json',
async: false,
url: 'json_demo.text', /*file location*/
success : function(data) {
console.log(data);
/*Do something with data*/
}
});
</script>
$.ajax({
键入:“GET”,
数据类型:“json”,
async:false,
url:'json_demo.text',/*文件位置*/
成功:功能(数据){
控制台日志(数据);
/*处理数据*/
}
});
试试这个
fetch(url)
.then((resp) => resp.text()) // you can use resp.json() for json
.then(function(data) {
// data handling
})
})
.catch(function(error) {
// If there is any error you will catch them here
});
fetch(url)
.then((resp) => resp.text()) // you can use resp.json() for json
.then(function(data) {
// data handling
})
})
.catch(function(error) {
// If there is any error you will catch them here
});