【问题标题】:remote autocomplete using ajax in codeigniter在codeigniter中使用ajax进行远程自动完成
【发布时间】:2017-02-11 03:31:48
【问题描述】:

我是 ajax 的新手,我从 google 获得了这段代码,现在我想从数据库中获取输入字段的数据,而不是定义的变量 availableTags。我很困惑,我想将 url 更改为要运行的特定函数。

这是我要添加的 URL,以便从数据库中获取值:

http://localhost:8888/auto/index.php/birds/get_birds

  $( function() {
    var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"
    ];
		
    function split( val ) {
      return val.split( /,\s*/ );
    }
    function extractLast( term ) {
      return split( term ).pop();
    }
        function log( message ) {
      $( "<input name='skill'>" ).text( message ).prependTo( "#log" );
      $( "#log" ).scrollTop( 0 );
    }
 
    $( "#tags" )
      // don't navigate away from the field on tab when selecting an item
      .on( "keydown", function( event ) {
        if ( event.keyCode === $.ui.keyCode.TAB &&
            $( this ).autocomplete( "instance" ).menu.active ) {
          event.preventDefault();
        }
      })
      .autocomplete({
        minLength: 0,
        source: function( request, response ) {
          // delegate back to autocomplete, but extract the last term
          response( $.ui.autocomplete.filter(
            availableTags, extractLast( request.term ) ) );
        },
        focus: function(event, ui) {
        
          $(event).val(ui.item.value);
          // prevent value inserted on focus
          return false;
        },
        select: function( event, ui ) {
          var terms = split( this.value );
          
          if(terms.length <= 3) {
          // remove the current input
          terms.pop();
          // add the selected item
          terms.push( ui.item.value );
          log(ui.item.value);
          if (jQuery.inArray(ui.item.value, availableTags) > -1) {
          	availableTags.splice($.inArray(ui.item.value, availableTags), 1);
            //availableTags[jQuery.inArray(ui.item.value, availableTags)] = '';
            terms.push( "" );
            // add placeholder to get the comma-and-space at the end
          	this.value = terms.join( ", " );
          }
          return false;
          }else{
                var last = terms.pop();
                $(this).val(this.value.substr(0, this.value.length - last.length - 2)); // removes text from input
                $(this).effect("highlight", {}, 1000);
                $(this).attr("style","border: solid 1px red;");
                return false;
            }
        },
        change: function (event, ui) {
            if (!ui.item) {
                $(this).val('');
            }
        }
      });
  } );
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Autocomplete - Multiple values</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <!-- <link rel="stylesheet" href="/resources/demos/style.css"> -->
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  </head>
<body>
 
<div class="ui-widget">
  <label for="tags">Tag programming languages: </label>
  <input id="tags" size="50">
</div>
 
 
</body>
</html>

控制器:

<?Php
class Birds extends CI_Controller{
function index(){
  $this->load->view('birds_view');
   }

function get_birds(){
$this->load->model('bird_model');
if (isset($_GET['term'])){
  $q = strtolower($_GET['term']);
  $data['s']=$this->bird_model->get_bird($q);
}

}
}  

型号:

<?php
class Bird_model extends CI_Model{
function get_bird($q){
$this->db->select('*');
$this->db->like('bird', $q);
$this->db->order_by('bird','desc');
$query = $this->db->get('birds');
if($query->num_rows() > 0){
  foreach ($query->result_array() as $row){
    $new_row['label']=htmlentities(stripslashes($row['bird']));
    $new_row['value']=htmlentities(stripslashes($row['id']));

    $row_set[] = $new_row; //build an array
  }
  echo json_encode($row_set); //format the array into json data
 }
 }
 }

【问题讨论】:

    标签: javascript jquery ajax codeigniter autocomplete


    【解决方案1】:

    尝试替换以下源代码

         source: function( request, response ) {
            $.ajax({
              url: "http://gd.geobytes.com/AutoCompleteCity",
              dataType: "jsonp",
              data: {
                q: request.term
              },
              success: function( data ) {
                response( data );
              }
            });
          },
    

    这里URL 是您的json 响应的路径。在控制器文件中生成 json 响应

      $( function() {
        var availableTags = [
          "ActionScript",
          "AppleScript",
          "Asp",
          "BASIC",
          "C",
          "C++",
          "Clojure",
          "COBOL",
          "ColdFusion",
          "Erlang",
          "Fortran",
          "Groovy",
          "Haskell",
          "Java",
          "JavaScript",
          "Lisp",
          "Perl",
          "PHP",
          "Python",
          "Ruby",
          "Scala",
          "Scheme"
        ];
    		
        function split( val ) {
          return val.split( /,\s*/ );
        }
        function extractLast( term ) {
          return split( term ).pop();
        }
            function log( message ) {
          $( "<input name='skill'>" ).text( message ).prependTo( "#log" );
          $( "#log" ).scrollTop( 0 );
        }
     
        $( "#tags" )
          // don't navigate away from the field on tab when selecting an item
          .on( "keydown", function( event ) {
            if ( event.keyCode === $.ui.keyCode.TAB &&
                $( this ).autocomplete( "instance" ).menu.active ) {
              event.preventDefault();
            }
          })
          .autocomplete({
            minLength: 0,
             source: function( request, response ) {
        $.ajax({
          url: "http://gd.geobytes.com/AutoCompleteCity",
          dataType: "jsonp",
          data: {
            q: request.term
          },
          success: function( data ) {
            response( data );
          }
        });
      },
            focus: function(event, ui) {
            
              $(event).val(ui.item.value);
              // prevent value inserted on focus
              return false;
            },
            select: function( event, ui ) {
              var terms = split( this.value );
              
              if(terms.length <= 3) {
              // remove the current input
              terms.pop();
              // add the selected item
              terms.push( ui.item.value );
              log(ui.item.value);
              if (jQuery.inArray(ui.item.value, availableTags) > -1) {
              	availableTags.splice($.inArray(ui.item.value, availableTags), 1);
                //availableTags[jQuery.inArray(ui.item.value, availableTags)] = '';
                terms.push( "" );
                // add placeholder to get the comma-and-space at the end
              	this.value = terms.join( ", " );
              }
              return false;
              }else{
                    var last = terms.pop();
                    $(this).val(this.value.substr(0, this.value.length - last.length - 2)); // removes text from input
                    $(this).effect("highlight", {}, 1000);
                    $(this).attr("style","border: solid 1px red;");
                    return false;
                }
            },
            change: function (event, ui) {
                if (!ui.item) {
                    $(this).val('');
                }
            }
          });
      } );
    <html lang="en">
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>jQuery UI Autocomplete - Multiple values</title>
      <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
      <!-- <link rel="stylesheet" href="/resources/demos/style.css"> -->
      <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
      <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
      </head>
    <body>
     
    <div class="ui-widget">
      <label for="tags">Tag programming languages: </label>
      <input id="tags" size="50">
    </div>
     
     
    </body>
    </html>

    【讨论】:

    • 我也在 if 条件中使用了该 availableTags 变量。我想在那边做什么改变?
    • 请分享您的AJAX URL方法的控制器代码
    猜你喜欢
    • 1970-01-01
    • 2011-10-11
    • 1970-01-01
    • 2012-06-03
    • 1970-01-01
    • 1970-01-01
    • 2013-02-20
    • 2011-04-15
    • 2011-09-16
    相关资源
    最近更新 更多