When i access this url: http://jservice.io/api/random the output is something like this:
[{
"id": 67917,
"answer": "agua",
"question": "After some fierce flamencoing, you might hear cries of this, Spanish for \"water\"",
"value": 800,
"airdate": "2004-11-18T12:00:00.000Z",
"created_at": "2014-02-11T23:29:50.743Z",
"updated_at": "2014-02-11T23:29:50.743Z",
"category_id": 1145,
"game_id": null,
"invalid_count": null,
"category": {
"id": 1145,
"title": "foreign words \u0026 phrases",
"created_at": "2014-02-11T22:52:16.443Z",
"updated_at": "2014-02-11T22:52:16.443Z",
"clues_count": 115
}
}]
I'm trying to use $.get()
to get the data of request:
<html>
<head>
<title>Quiz</title>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
</body>
<script>
$.get("http://jservice.io/api/random", function(data, status){
alert("Data: " + data.title + "\nStatus: " + status);
});
</script>
</html>
But the output is this:
Data: undefined
Status: success
There is no data.title
.
data
is an array. title
is nested under the array element's category
. For this specific response, you'd need (roughly):
data[0].category.title
But if you can get multiple results back, you need to decide what you're actually going to do.
The return was an array. So you have to use data[0]
. Also the title
is inside the category
object. Try this.
$.get("http://jservice.io/api/random", function(data, status){ alert("Data: " + data[0].category.title + "\\nStatus: " + status); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The result can also be achieved by accessing the url as json object. Sharing below code for reference.
<html>
<head>
<title>Quiz</title>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
</body>
<script>
(function() {
var srcURL = "http://jservice.io/api/random";
$.getJSON( srcURL, {
format: "json"
})
.done(function( data ) {
$.each( data, function( i, item ) {
console.log(item.category.title);
});
});
})();
</script>
</html>
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.