The similar questions didnt work for me. I have a AJAX GET request. When I show the entire json in the console log it works, but I cant select a single object from it.
My JS
$.ajax({
type: "GET",
url: "http://localhost:8092/api/getdata",
dataType: "json",
success: function (data) {
console.log(data["date"]);
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
This code returns undefined
but if I only use console.log(data)
it shows everything. Not sure what to do from here.
This is the output when I use console.log(data)
{
"date": "04-06-2020",
"id": 4
}
SS when I use console.log(data)
SS when I use console.log(data["id"])
It seems you didn't show us the complete output of console.log(data)
in your question, there are square brackets ( [ ]
) missing around it, According to your console screenshot, you get an array , with one object in it.
So the structure is:
[
{
"date": "04-06-2020",
"id": 4
}
]
Therefore, you need to access the first array element (using [0]
) to get the object itself, and from there the property date
, like this:
console.log(data[0].date)
(Of course, data[0]["date"]
works too, but in my opinion the dot-based property access looks cleaner.)
data["date"]
is used for object which has date attribute. But in your response is an array you need to say data[0]["date"]
or data[0].date
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.