I'm defining the following action to happen when pressing a button on my HTML:
$(document).ready(function() {
$("#query").keydown(function () {
// stuff
$.get(url, function (result) {
console.log(result);
var list = "";
for (var i = 0, l = result["results"].length; i < l; i++) {
list += '<li>' + result["results"][i]["label"] + '</li>';
}
list = "Here are some results: <ul>" + list + "</ul>";
});
});
What arrives in "result" is a JSON array in the following form:
{"results":[{"label":"something"},{"label":"something else"},{"label":"many other ones"}]}
So, why is my reference to length
being interpreted as a reference to the property of a null value?
I believe you are getting a json input. You forgot to convert the json into an actual Javascript Object. You can do so with one of the two following ways.
$(document).ready(function() {
$("#query").keydown(function () {
// stuff
$.get(url, function (result) {
result = JSON.parse(result);
console.log(result);
var list = "";
for (var i = 0, l = result["results"].length; i < l; i++) {
list += '<li>' + result["results"][i]["label"] + '</li>';
}
list = "Here are some results: <ul>" + list + "</ul>";
});
Or
$(document).ready(function() {
$("#query").keydown(function () {
// stuff
$.getJSON(url, function (result) {
console.log(result);
var list = "";
for (var i = 0, l = result["results"].length; i < l; i++) {
list += '<li>' + result["results"][i]["label"] + '</li>';
}
list = "Here are some results: <ul>" + list + "</ul>";
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With