js reads the data instance in the json file fragment

  • 2021-08-03 08:18:39
  • OfStack

In html, js is used to read the data returned from the server side of the dynamic website and display it

1. js. html page

Need to introduce an js file that executes jquery


<HTML> 
<HEAD>  
<META name=Generator content=EditPlus> 
<META name=Author content=""> 
<META name=Keywords content=""> 
<META name=Description content=""> 
<script src="jquery-1.8.2.min.js"></script>  
<script>  
$(function(){  
//$("#loaddata").click(function(){  
$(document).ready(function(){   
// Use getJSON Method read json Data ,   
// Note: info.json It can be a different type of file as long as the data in it is json Type is sufficient    
$.getJSON('info.json',function(data){    
var html = '';    
$.each(data,function(i,item){    
html += '<TR><TD>'+item['name']+'</TD>'+    
'<TD>'+item['sex']+'</TD>'+    
'<TD>'+item.address+'</TD>'+    
'<TD>'+item['home']+'</TD></TR>';    
});    
$('#title').after(html);    
//after Method : Insert content after each matching element.   
});  
}); 
});  
// Note : It can be item.address, It can also be item['address'] 
//firefox Newspaper  json In a file   "Syntax error  [ " , Single can load data  //ie chrome  Unable to load data  
</script> 
<INPUT id=loaddata value= Load data  type=button>  
<TABLE id=infotable><TBODY><TR id=title><TH> Name </TH><TH> Gender </TH><TH> Address </TH><TH> Home page </TH></TR></TBODY></TABLE>

info. json file


[ 
{ 
"name":"jb51", 
"sex":"man", 
"address":"hangzhou", 
"home":"https://www.ofstack.com"
}, 
{ 
"name":"lisi", 
"sex":"wumen", 
"address":"beijing", 
"home":"http://yulu.ofstack.com"
} 
] 

Download online

jquery-1.8.2.min.js

Application scenario:

Periodically read from the database of specific records on the static page display, in order to reduce the pressure of access to the database, the number of specific records are taken out and stored in json, page access links do not need to request the database in real time.

At this point, you can load the contents in json into html static.

-------------QA

It is indeed a coding problem that can't display Chinese. The default saved json must be a Notepad, and then the suffix is changed to json. The default code of Notepad is ANSI. It is naturally problematic to display Chinese.

Solution: Open the. json file file-save as see the encoding format below it, select UTF-8 can be.

There is another error-prone place here:

Request json file to report 405 error, obviously the path is right, but it still reports error.

Solution: Modify the request mode to get request.


Related articles: