I need to get the name from JSON file what is wrong wit this code? i would like to get the name value from each of the results and add them to the body.
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="crossorigin="anonymous"></script>
<script>
$.ajax({
type: "GET",
dataType: "json",
url: "https://wger.de/api/v2/exercise.json?category=8&language=2",
success: function(data){
$.each(data,function(index,object){
$("body").append("<div>"+object.name +"</div><br/>")
})
}
});
</script>
</head>
<body>
</body>
</html>
The only problem is that you are using the wrong object to iterate.
if you run this snippet you can see the returned object on the console.
$.ajax({ type: "GET", dataType: "json", url: "https://wger.de/api/v2/exercise.json?category=8&language=2", success: function(data){ console.log(data) } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
as you can see, you need to iterate over data.results
, so this code should work:
$.ajax({
type: "GET",
dataType: "json",
url: "https://wger.de/api/v2/exercise.json?category=8&language=2",
success: function(data){
if(data.results){
$.each(data.results,function(index,object){
$("body").append("<div>"+object.name +"</div><br/>")
})
}
}
});
The data
argument supplied to the success callback comes in as an Object with a results property that is an Array of Objects.
Rather than passing in the whole data
object to $.each you should just give it the results array like so:
success: function(data){
$.each(data.results, function(index, object){
$("body").append("<div>"+object.name +"</div><br/>")
})
}
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.