简体   繁体   English

jQuery使用AJAX JSON自动完成

[英]jQuery autocomplete with AJAX JSON

I'm trying to have dynamic autocomplete values for a textbox. 我正在尝试为文本框设置动态自动完成值。

This is my response: 这是我的回应:

echo json_encode($res)

0: {type_name: "name1"}
1: {type_name: "name2"}
2: {type_name: "name3"}
3: {type_name: "name4"}
4: {type_name: "name5"}

And this is my autocomple ajax code: 这是我的自动完成的ajax代码:

 $( "#txt_box" ).autocomplete({
  source: function( request, response ) {
      $.ajax({
        type:"POST",
        url: "index.php?action=autocomplete",                   
        dataType: "json",
        data: {
            q: request.term
        },
        success: function( data ) {
            response( data );
        }
    });
  }
 });    

I'm not able to figure out if there is any issue in my JSON format or in my AJAX code. 我无法确定JSON格式或AJAX代码是否存在任何问题。 I'm not able to get the autocomplete dropdown based on the keysearch. 我无法根据关键字搜索获得自动完成下拉列表。

As described in http://api.jqueryui.com/autocomplete/#option-source , the data object passed to the response callback can be either an array of strings or array of objects with label and value properties. http://api.jqueryui.com/autocomplete/#option-source中所述 ,传递给response回调的data对象可以是字符串数组或具有labelvalue属性的对象数组。 Your response does not seem to be any of these. 您的回应似乎不是这些。

So either you have to fix your response, to provide eg [ "name1", "name2", "name3", "name4", "name5" ] (ie array of strings), or you must process this response in your success callback, to forward the data to the response callback in a correct format. 因此,要么必须修复响应,以提供例如[ "name1", "name2", "name3", "name4", "name5" ] (即字符串数组),要么必须在success回调中处理此响应,以正确的格式将数据转发到response回调。

Don't call ajax request into the autocomplete function. 不要在自动完成功能中调用ajax请求。 As per your requirement, first you need to collect data json format: 根据您的要求,首先您需要收集数据json格式:

var jsonData = ["name1","name2","name3",.......];
$( "#txt_box" ).autocomplete({ source:jsonData });   

Please follow the link: https://jqueryui.com/autocomplete/ 请点击以下链接: https : //jqueryui.com/autocomplete/

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

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