我正在使用Django框架进行Web开发。我想阅读一个JSON文件并在网页上打印它的内容。
这是我的剧本:
<script type="text/javascript"
src = "file:///home/pragna/myproject/myapp/templates/myapp/segment2.json">
</script>
<script>
var mydata = JSON.parse(jsonstr);
alert(mydata[0].text);
</script>
我已将JSON文件存储为以下格式:
jsonstr = [
{
"text": "this is the text",
"name" : "thisisme"
},
{
"text": "some more text",
"name" :"thisisaname"
}
]
当我运行服务器时,网页请求文件时没有404错误,但是,也没有出现警报。
答案 0 :(得分:1)
当我运行服务器时,网页上没有404错误 请求文件
您所说的服务器中没有404错误。浏览器控制台仍会显示404错误,因为您使用file:/// url加载JSON。
<script type="text/javascript", src ="file:///home/pragna/myproject/myapp/templates/myapp/segment2.json"> </script>
这应该是http://,https://或者像/segment2.json这样的相对网址
答案 1 :(得分:0)
您不需要解析内容,因为它已经是JSON。
试试这个:
<script type="text/javascript" src ="file:///home/pragna/myproject/myapp/templates/myapp/segment2.json"></script>
<script>
alert(jsonstr[0].text);
</script>
应该有用。
那就是说,XmlHttpRequest是我认为更好的方法。
答案 2 :(得分:0)
无需解析
alert('{{ jsonstr.0.text }}');
答案 3 :(得分:0)
您将获得 404 ,因为您尝试使用file:///
前缀访问本地计算机内的文件,这是您的真实演示:
<script type="text/javascript" src ="http://www.mocky.io/v2/5797d7190f00005c0ef0809e"></script>
<script type="text/javascript">
alert(jsonstr[0].text);
</script>