I have problem with "jQuery template" when using Json file. when i use below code, i got no errors however it doesn't work.
The problem is solved when I define the contents of a data Json as a variable. But whenever I try to use the Json file, it doesn't work
I was very excited about this but didn't find anything. Please guide me.
<script type="text/javascript">
$(function() {
jQuery.getJSON("js/data.json", function(myData) {
$("#ourTemplate").tmpl(myData).appendTo("#tableContent");
});
})
</script>
<script id="ourTemplate" type="text/x-jquery-tmpl">
<tr>
<td>${username}</td>
<td>${name}</td>
<td>${skills}</td>
<td>${age}</td>
</tr>
</script>
<!DOCTYPE html>
<html lang="fa" dir="ltr">
<title>jQuery templates</title>
<head>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" charset="utf-8"></script>
<script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js" charset="utf-8"></script>
</head>
<body>
<table border="1">
<thead>
<th>username</th>
<th>name</th>
<th>skills</th>
<th>age</th>
</thead>
<tbody id="tableContent">
</tbody>
</table>
</body>
</html>
[{
name: "milad",
username: "mldv404",
skills: "php , javascript , css , jQuery",
age: 24,
},
{
name: "hamid",
username: "hamidJ",
skills: "Mysql , javascript , css , jQuery",
age: 25,
},
{
name: "hossein",
username: "hosseindavari",
skills: "java , simpless , document , jQuery",
age: 34,
},
{
name: "davood",
username: "davoodSun",
skills: "visial Basic , dot net7 , c++ , jQuery",
age: 24,
},
{
name: "zahra",
username: "sunMedia",
skills: "python , hibernate , AJax , PostgerSql",
age: 24,
},
{
name: "mohsen",
username: "msnv",
skills: "vbScript , php , javascript , jQuery",
age: 24,
},
{
name: "mahdi",
username: "mhdi23",
skills: "php , javascript , css , jQuery",
age: 24,
},
];
The problem is solved when I define the contents of a data Json as a variable
That's because your "JSON" isn't actually JSON; it's just a regular JavaScript object. See here for more info: https://stackoverflow.com/a/3975890/7290573
Change the contents of your JSON file to the following and it will work (notice the quotes around the key names):
[
{
"name": "milad",
"username": "mldv404",
"skills": "php , javascript , css , jQuery",
"age": 24
},
{
"name": "hamid",
"username": "hamidJ",
"skills": "Mysql , javascript , css , jQuery",
"age": 25
},
{
"name": "hossein",
"username": "hosseindavari",
"skills": "java , simpless , document , jQuery",
"age": 34
},
{
"name": "davood",
"username": "davoodSun",
"skills": "visial Basic , dot net7 , c++ , jQuery",
"age": 24
},
{
"name": "zahra",
"username": "sunMedia",
"skills": "python , hibernate , AJax , PostgerSql",
"age": 24
},
{
"name": "mohsen",
"username": "msnv",
"skills": "vbScript , php , javascript , jQuery",
"age": 24
},
{
"name": "mahdi",
"username": "mhdi23",
"skills": "php , javascript , css , jQuery",
"age": 24
}
]