简体   繁体   中英

AJAX request, filtered JSON response html/javascript

when I request a .json containing person info (firstname, lastname) from my node.js server, I would like to filter that data depending on what the user inputs.

Example: I request the .json from the server, this gives me a list of people, but as I start typing in the text 'form' the list get filtered to match what I typed.

I have some problems with this, first, how can I display this .json as a list? as of now, I display it like this:

var parsed = JSON.parse(xmlHttp.responseText);
var html = '';
for (var i = 0; i < parsed.length; i++) {
    html += '<div>' + parsed[i] + '</div>';
}
document.getElementById("myDiv").innerHTML = html;
}

example of .json

 "firstName": "John",
 "lastName": "Doe",

I'm sure I can manage the filtering, just need a push with the list!

Shoutout to 'Zub' for helping me with the request

Currently you are outputting objects , you need to output the properties on these objects:

var parsed = JSON.parse(xmlHttp.responseText);
var html = '';
for (var i = 0; i < parsed.length; i++) {
    html += '<div>' + parsed[i].firstName + '-' + parsed[i].lastName + '</div>';
}
document.getElementById("myDiv").innerHTML = html;
}

As for the filtering, you'd need to attach to an event for the input you want to filter with (example onkeypress). In the handler, you should clear out the html, run over the original list again, but put in a condition that only adds to the html when it matches your query. I'll leave that up to you

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