简体   繁体   中英

Error in getting data from JSON Object

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:

  1. all simultaneously in 1 link
  2. all by 4 seperately in 4 links

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

Accessing your data:

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...

  1. First you need to make sure that the handler attached after the data came back from the server
    1. second you need to remove the (,) after the last JSON employee.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM