jquery自动完成,解析数据

时间:2017-10-25 15:33:30

标签: javascript jquery parsing autocomplete

我使用jquery自动完成:

页面无论如何返回:

Array [ Object, Object, Object, Object ]

对象具有id:INTEGER和value:STRING

ele.autocomplete({
    minLength: 1,               
    delay: 150,             
    source: function(request, response) {
        jQuery.ajax({
            url: "whatever",
            data: {                         
                term: request.term
            },
            dataType: "json",
            success: function(data) {
                 response(data);                                                

                /* this actually works id is correctly logged
                data.forEach(function(element) {
                     console.log(element.id);
                });*/


            }
         });
     },             
     select: function(e, ui) {
        //do i have to do something here? (i guess)
     }
 });

我想要完成的(我无能为力)是:当我从自动完成菜单中选择一个值时,输入(ele)值会更改为相应的id,而它的“text”仍然是字符串值

我该怎么办?提前谢谢

1 个答案:

答案 0 :(得分:0)

好的,如果有人需要,仅供将来参考:

 response(data); is not ok

 response($.map(data, function(item) {
      return {
         value: item.id,  //set the value property with id integer
         label: item.value  //set the label property with "value" string 
       };
 }));

然后

select: function(e, ui) {       //when selecting an element from the list
    var keyid = ui.item.value;  //get value wich now contains id
    var keylab = ui.item.label; //and the label wich contains the string
    console.log(keyid + ' - ' + keylab); //do what you have to do
}