Heim  >  Artikel  >  Web-Frontend  >  利用js读取动态网站从服务器端返回的数据_javascript技巧

利用js读取动态网站从服务器端返回的数据_javascript技巧

WBOY
WBOYOriginal
2016-05-16 17:00:571987Durchsuche

在html中利用js读取动态网站从服务器端返回的数据进行显示

1、js.html 页面

需要引入 执行jquery的js文件

复制代码 代码如下:




New Document






<script> <br><br>$(function(){ <BR>//$("#loaddata").click(function(){ <BR>$(document).ready(function(){ <BR>//使用getJSON方法读取json数据, <BR>//注意:info.json可以是不同类型文件,只要其中的数据为json类型即可 <BR>$.getJSON('info.json',function(data){ <br><br>var html = ''; <BR>$.each(data,function(i,item){ <BR>html += '<tr><td>'+item['name']+''+ <BR>'<td>'+item['sex']+''+ <BR>'<td>'+item.address+''+ <BR>'<td>'+item['home']+''; <BR>}); <BR>$('#title').after(html); <BR>//after方法:在每个匹配的元素之后插入内容。 <BR>}); <BR>}); <BR>}); <br><br>//注:可以是item.address,也可以是item['address'] <BR>//firefox报 json文件中 “语法错误 [”,单能加载数据 <BR>//ie chrome 无法加载数据 <BR></script>






姓名 性别 地址 主页




info.json文件
复制代码 代码如下:

[
{
"name":"zhangsan",
"sex":"man",
"address":"hangzhou",
"home":"http://www.zhangsan.com"
},
{
"name":"lisi",
"sex":"wumen",
"address":"beijing",
"home":"http://www.lisi.coms"
}
]

应用场景 :

定期从数据库中读取的特定记录放到静态页面上去展示,为了减少对数据库访问的压力,把特定记录数取出来存放在json中,页面访问链接不用实时请求数据库。

至此可以将json中的内容加载到html静态也中去。

显示不了中文的确是编码问题,默认保存的json肯定是个记事本,然后改后缀名为json的,记事本默认编码是ANSI的 显示中文自然有问题,

解决方法:打开.json文件 文件 - 另存为 看到下面编码格式了吧 选择UTF-8 就可以了。

这里还有个容易出错的地方:
请求json文件报405错误,明明路径对的 但是还是报错。
解决方法:修改请求方式为get请求:
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn