We want to bind json response to li elements with each element having value as id and text as name.
$.ajax({
type: "GET",
url: "/api/xyz/",
dataType: "json",
success: function(response) {
var items = [];
$.each(response, function(i, item) {
items.push('<li</li>",{value:item.id,text:item.name}');
});
$('#formFieldCity ul').append(items.join(''));
}
});
But no success, I don't see any binding. Can anyone help?
I think you mean
var list = $('#formFieldCity ul'); //caching
$.ajax({
type: "GET",
url: "/api/xyz/",
dataType: "json",
success: function (response) {
var items = [];
//Misplaced variable here: data instead of response
$.each(response, function(i, item) {
var mapped = {value:item.id,text:item.name};
items.push(mapped)
list.append("<li id=\""+item.id+"\">"+item.name+"</li>");
});
}
});
This will basically print a json in your HTML. Hope I got what you wanted.
EDIT: If your response is an array, consider using a simple for loop, which is about 8x faster then the jQuery.each
for(var i=0; i<response.length; i++){
var mapped = {value:response[i].id,text:response[i].name};
items.push(mapped)
list.append("<li id=\""+mapped.value+"\">"+mapped.text+"</li>");
}
you should write like this:
$.each(data, function(i, item) {
items.push('<li id="'+item.id+'">'+item.name+'</li>');
});
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.