【问题标题】:jquery autocomplete not displaying the values of arrayjquery自动完成不显示数组的值
【发布时间】:2014-01-15 08:07:05
【问题描述】:

嗨,我正在使用带有 codeigniter 的 jquery 自动完成,我的 reslut 数组来自数据库,我正在使用 json_encode() 发回数组。但作为回应,我无法在搜索中显示值但我得到空结果,这意味着我得到值但我无法显示但值即将到来我可以看到空的 lis,我的数据数组是这样的

[{"countryid":"1","countryname":"Afghanistan"},{"countryid":"2","countryname":"Albania"},{"countryid":"3","countryname":"Algeria"},{"countryid":"4","countryname":"American Samoa"},{"countryid":"5","countryname":"Andorra"}]

我的模型函数是这样的

public function search_countries($string)
    {
        $this->db->like('countryname', $string);
        $query = $this->db->get('countries');
        return $query->result_array();
    }

我的控制器功能是这样的

public function search_countries()
    {
        $string = $this->input->post('countryname');
        $data = $this->user_m->search_countries($string);
        $this->output->set_header('Content-Type: application/json; charset=utf-8');
        echo json_encode($data);
    }

这里是jquery函数

$( ".country" ).autocomplete({
      source: function( request, response ) {
        $.post("signup/search_countries", {countryname: request.term}, function(data){
            response(data, function( data ) {
              return {
                label: data.countryid,
                value: data.countryname
              }
            });
        });
      }
    });

【问题讨论】:

  • 您需要使用正确的键,如返回 json。
  • 键是正确的@cubuzoa
  • 你也检查过你在萤火虫上的响应数据吗?它是否正确并且您没有收到任何 js 错误?

标签: javascript php jquery arrays codeigniter


【解决方案1】:

这不应该是:

            label: data.countryid,
            value: data.countryName

作为:

            label: data.countryid,
            value: data.countryname

按照您收到的实际 json 响应(将 countryName 中的 Name 更改为 name)。

【讨论】:

  • @ahmadgulzar 那么你应该在上面的问题中更正它,因为它仍然显示 contryName,而你的 json 响应显示 countryname。
  • @ahmadgulzar 你在用萤火虫吗?你能检查一下,如果你甚至没有收到来自服务器的任何响应吗?也可以尝试做一些类似console.log(data) 的事情,这样我们就可以确定它只是一个字符串还是实际转换为一个 JS 对象。跨度>
  • 是的,我正在收到回复。当我在 alert() 中获得值时,它会显示如下 [object object]
【解决方案2】:

我只给js部分;

$( ".country" ).autocomplete({
      source: function( request, response ) {
        $.post("signup/search_countries", {countryname: request.term}, function(data){
            response($.map( data, function( item ) {
              return {
                label: item.countryname,
                value: item.countryid
              }
            }));
        });
      }
    });

你能试试这个吗?

【讨论】:

  • 谢谢,但它不起作用。它显示结果,但在空列表中。我也可以悬停,但这些是空白元素
  • 您能检查一下您的响应 json 密钥吗?
  • 好的,我更新了代码。请你再试一次。我忘了用地图
  • 感谢@cubuzoa 它有效,但我纠正了一些错误。它奏效了
猜你喜欢
  • 1970-01-01
  • 2018-01-15
  • 1970-01-01
  • 1970-01-01
  • 2018-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-26
相关资源
最近更新 更多