我正在尝试将 json 数据从本地路径加载到一个简单的 html 页面。我尝试了很多方法来使用 fetch、ajax 加载数据。我需要从 json 读取值并在 html 页面中更新相同的值。
我需要托管这个页面,这将被拥有自己的浏览器的人使用。
window.addEventListener('load', function() {
console.log('All assets are loaded')
})
let request = new Request("./test.json")
fetch(request)
.then(function(resp){
return resp.json();
})
.then(function(data){
for(var i in data){
console.log(i+data[i])
document.getElementById(i).style.background = data[i]
}
})
<html>
<style type="text/css">
.tableLayout {
display:table;
}
.tableLayout > div{
display:table-row;
}
.tableLayout > div > div {
display:table-cell;
border:solid;
text-align: center;
}
.Table
{
display: table;
}
.Title
{
display: table-caption;
text-align: center;
font-weight: bold;
font-size: larger;
}
.Heading
{
display: table-row;
font-weight: bold;
text-align: center;
}
.Row
{
display: table-row;
display:grid;
}
.fixed {
table-layout: fixed;
display:grid
}
.Cell
{
display: table-cell;
border: solid;
border-width: thin;
padding-left: 26px;
padding-right: 26px;
text-align: center;
}
.Cell2
{
display: table-cell;
border: solid;
border-width: thin;
padding-left: 56px;
padding-right: 34px;
text-align: left;
}
.Cell3
{
display: table-cell;
border: solid;
border-width: thin;
padding-left: 56px;
padding-right: 35px;
text-align: center;
}
</style>
<body>
<header>
<meta http-equiv="refresh" content="30">
<h1> JSon Example </h1>
<script src ="Json_Development_Test.js">
</script>
</header>
<div class="Heading">
<div Class="Cell">
<p>Project Name</p>
</div>
<div Class="Cell">
<p>Service URL</p>
</div>
<div id="test">
<span id="headerID1" class="Cell">
<p>PDC</p>
</span>
<span id="headerID2" class="cell">
<p>DDC</p>
</span>
<span id ="Time" class="Cell">
<P> Updated Checked Time</P>
</span>
</div>
</div>
<div class="Heading">
<div Class="Cell">
<p>GRapd</p>
</div>
<div Class="Cell">
<p>abc.com</p>
</div>
<div id ="Test">
<span id="Pdata1" class="Cell2">
<p>cp</p>
</span>
<span id="Ddata1" class="Cell2">
<p>de</p>
</span>
<span id ="tdata1" class="Cell2">
<P> </P>
</span>
</div>
</div>
</div>
<div class="Heading">
<div Class="Cell">
<p>LEPRD</p>
</div>
<div Class="Cell">
<p>bcd.com</p>
</div>
<div id="test">
<span id="pdata2" class="Cell2">
<p>HTP</p>
</span>
<span id="ddata2" class="Cell2">
<p>HcP</p>
</span>
<span id ="tdata2" class="Cell2">
<P> </P>
</span>
</div>
</div>
</body>
</html>
以上都在某些浏览器中按预期工作,但不是在所有浏览器中。
预期:来自 josn 的数据应该在所有浏览器中加载。我想知道哪种方法应该是从本地文件路径加载 json 的简单和最佳方法。
实际:上述java脚本未在所有浏览器中加载数据
不幸的fetch
是,并非所有浏览器(即 Internet Explorer)都支持该api,因此您必须使用 XMLHttpRequest api 或者您可以使用 jquery ajax 调用 api,因为 jquery 将处理跨浏览器问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句