首页 > 解决方案 > 从 1 个自动完成输入中自动填充 2 个表单输入,以从一个东西中查找代码和价格

问题描述

我有一个自动完成输入,它将自动填写其他 2 个输入,在这种情况下我使用 json,我的问题是当我在水果名称输入中输入 2 个字符时,它会显示数据库中的所有数据,而它应该仅根据我输入的内容显示数据,但如果我使用第 13 行的“var json”,它将按我的预期显示数据,当我在第 16 行使用源时,它将显示所有数据我有,如果我的代码有错误?如果您能帮助我,我将不胜感激

<head>
  <link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
</head>
<div>
  <input type="text" id="secondInput" name="code" value="" placeholder="Code" readonly>
  <input type="text" id="field" name="fruit" value="" placeholder="Fruit name(input here)">
  <input type="text" id="thirdInput" name="price" value="" placeholder="Price" readonly="" onkeypress="return isNumber(event)" maxlength="12">
</div>
<script type="text/javascript">
    $(function() {
        //var json = [{"code": "1","label": "Apple","price": "10000"},{"code": "17","label": "Banana","price": "20000"}];
        $("#field").autocomplete({
            //source: json,
      source: "<?= site_url('home/take_json_fruit'); ?>",
      data: { fruit: $("#field").val()},
      minLength: 2,
      dataType: "json",
      select: function(event, ui) {
       $("#secondInput").val(ui.item.code);
       $("#thirdInput").val(ui.item.price);
     },

     change: function (event, ui) {
       if (ui.item === null) {
        $(this).val('');
        $('#field_id').val('');
      }
    }
  });
        $("#field").focusout(function() {
            if ($("#field").val() === '') {
                $('#field_id').val('');
            }
        });
    });
</script>

这是我在控制器 className Home 中的功能

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Home extends CI_Controller {
  public function __construct()
  {
    parent::__construct();
    $this->load->helper('url');
    $this->load->library('session');
    $this->load->model('Json_decode');
  }
  public function take_json_fruit()
  {
    $fruit = $this->input->post('fruit');
    $rows = $this->Json_decode->take_fruit_json($fruit);
    echo json_encode($rows);
  }
}

这是我的模型类名 Json_decode

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Json_decode extends CI_Model {
  public function take_fruit_json($fruit)
  {
    $this->db->select('code_fruit as code, fruit as label, price_fruit as price');
    $this->db->like('fruit', $fruit);
    $query = $this->db->get('fruits');
    return $query->result();
  }
}

标签: javascriptjquerycodeigniter

解决方案


codeigniter 的查询构建器类中的类似将 % 放在术语之前和之后。这就是为什么您(显然)获得许多额外结果的原因。尝试第三个可选参数,例如:

$this->db->like('fruit', $fruit, 'after');

基于查询生成器类的 CI 文档


推荐阅读