I have a JSON data as info.json.
[
{"employee": {"name":"A", "salary": "324423"}},
{"employee": {"name":"B", "salary": "43111"}},
{"employee": {"name":"C", "salary": "43434"}},
{"employee": {"name":"D", "salary": "120000"}},
]
and index.html as link linklinklink
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
var item,$emp=$('#emp') ;$aa=$('a') ;$sal=$('#salary');
$.ajax({
url:"info.json",
success:function(data){
item=data;
}
})
$aa.click(function(){
var index=$aa.index(this);
var
inf=item[index].employee;
$sal.text(inf.salary);
return false;
})
</script>
I just want to display name and salary of the employee on the click button from JSON DATA in index.html:
But getting error as:
I think it is simple but I am new to AJAX. THANKS IN ADVANCE
your JSON have an extra comma in the last line, remove it
your code is getting the json data but not parsing it, use this
$.ajax({
url: "info.json",
success: function(data) {
item = JSON.parse(data);
}
})
now you have you data in item
Number of employees is item.length
1st employee name is item[0].employee.name
1st employee salary is item[0].employee.salary
2nd employee name is item[1].employee.name
2nd employee salary is item[1].employee.salary
and so on...
this is the JSON:-
[
{"employee": {"name":"A", "salary": "324423"}},
{"employee": {"name":"B", "salary": "43111"}},
{"employee": {"name":"C", "salary": "43434"}},
{"employee": {"name":"D", "salary": "120000"}}
]
this is the code:-
var item, $emp = $('#emp');
$aa = $('a');
$sal = $('#salary');
$.ajax({
url: "info.json",
success: function(data) {
//item = data;
//handle click only after the data came back
handleClick(data);
},
error:function(xhr,status,error){
console.log(error);
}
})
var handleClick = function(item){
$aa.click(function() {
var index = $aa.index(this);
debugger;
if (item) {
var
inf = item[index].employee;
$sal.text(inf.salary);
$emp.text(inf.name);
}
return false;
})
}
Here is a full Demo
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.