简体   繁体   English

jQuery从json响应中向ul元素的li添加值和文本

[英]jquery add value and text to li of ul elements from json reponse

We want to bind json response to li elements with each element having value as id and text as name. 我们想将json响应绑定li元素,每个元素的值分别为id和text作为名称。

$.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. 这基本上将在您的HTML中打印一个json。 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循环,这比jQuery.each快8倍

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>');
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM