Home  >  Article  >  Web Front-end  >  Use js to read data returned from the server side by dynamic websites_javascript skills

Use js to read data returned from the server side by dynamic websites_javascript skills

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

Use js in html to read the data returned from the server side of the dynamic website for display

1. The js.html page

needs to introduce the js file that executes jquery

Copy code The code is as follows:




New Document






<script> <br><br>$(function(){ <br>//$("#loaddata").click(function(){ <br>$(document).ready(function(){ <br>//Use the getJSON method to read json data, <br>//Note : info.json can be different types of files, as long as the data in it is of json type <br>$.getJSON('info.json',function(data){ <br><br>var html = ''; <br>$.each(data,function(i,item){ <br>html = '<tr><td>' item['name'] '</td>' <br>'<td&gt ;' item['sex'] '</td>' <br>'<td>' item.address '</td>' <br>'<td>' item['home'] ' </td></tr>'; <br>}); <br>$('#title').after(html); <br>//after method: insert after each matching element content. <br>}); <br>}); <br>}); <br><br>//Note: It can be item.address or item['address'] <br>//firefox report "Syntax error [" in json file, data can only be loaded<br>//ie chrome cannot load data<br></script>






< /table>



info.json file
Copy code The code is as follows:

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

Application scenario:

Specific records read from the database regularly are put on static pages for display. In order to reduce the pressure on database access, the number of specific records is taken out and stored in json. Page access link There is no need to request the database in real time.

Now you can load the content in json into static html.

The inability to display Chinese is indeed an encoding problem. The json saved by default must be Notepad, and then the suffix is ​​changed to json. The default encoding of Notepad is ANSI, so there is naturally a problem in displaying Chinese.

Solution: Open the .json file - Save as and see the encoding format below. Just select UTF-8.

There is another error-prone place here:
Requesting a json file reports a 405 error. The path is obviously correct, but an error is still reported.
Solution: Modify the request method to get request:
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
NameGenderAddressHomepage