2014-10-04 1 views
0

나는 하루 종일 자동 완성 스크립트를 만들려고했지만 그걸 알아낼 수 없습니다.PHP/자바 스크립트에서 양식 자동 완성

<form method="POST"> 
    <input type="number" id="firstfield"> 

    <input type="text" id="text_first"> 
    <input type="text" id="text_sec"> 
    <input type="text" id="text_third"> 

</form> 

이것은 내 html입니다. 내가 뭘하려고 다음과 같이 첫 번째 필드 를 자동 완성 아약스를 사용하는 것입니다 preview

첫 번째 입력 9 개 숫자가있는 경우는 다른 입력뿐만 아니라 함께 올바른 링크 된 데이터를 채우고

ajax.php에

스크립트 서버에 mysqli_query을 전송하고 모든 데이터 요청 (표 : 필드 || 행 : 횟수, 우선, 초, 제 3 호)

+0

https://twitter.github.io/typeahead.js/ – Rob

+0

그게 내 뜻이 아니예요. 당신이 내게 준 예제는 목록이 있는데, 이미지 에서처럼 입력을 완료하지 못합니다. – Kygran

+0

정확히 그 일을합니다. . – Rob

답변

0

https://github.com/ivaynberg/select2

PHP 통합 예 :

<?php 
/* add your db connector in bootstrap.php */ 
require 'bootstrap.php'; 

/* 
$('#categories').select2({ 
    placeholder: 'Search for a category', 
    ajax: { 
     url: "/ajax/select2_sample.php", 
     dataType: 'json', 
     quietMillis: 100, 
     data: function (term, page) { 
      return { 
       term: term, //search term 
       page_limit: 10 // page size 
      }; 
     }, 
     results: function (data, page) { 
      return { results: data.results }; 
     } 

    }, 
    initSelection: function(element, callback) { 
     return $.getJSON("/ajax/select2_sample.php?id=" + (element.val()), null, function(data) { 

       return callback(data); 

     }); 
    } 

}); 
*/ 

$row = array(); 
$return_arr = array(); 
$row_array = array(); 

if((isset($_GET['term']) && strlen($_GET['term']) > 0) || (isset($_GET['id']) &&  is_numeric($_GET['id']))) 
{ 

if(isset($_GET['term'])) 
{ 
    $getVar = $db->real_escape_string($_GET['term']); 
    $whereClause = " label LIKE '%" . $getVar ."%' "; 
} 
elseif(isset($_GET['id'])) 
{ 
    $whereClause = " categoryId = $getVar "; 
} 
/* limit with page_limit get */ 

$limit = intval($_GET['page_limit']); 

$sql = "SELECT id, text FROM mytable WHERE $whereClause ORDER BY text LIMIT $limit"; 

/** @var $result MySQLi_result */ 
$result = $db->query($sql); 

    if($result->num_rows > 0) 
    { 

     while($row = $result->fetch_array()) 
     { 
      $row_array['id'] = $row['id']; 
      $row_array['text'] = utf8_encode($row['text']); 
      array_push($return_arr,$row_array); 
     } 

    } 
} 
else 
{ 
    $row_array['id'] = 0; 
    $row_array['text'] = utf8_encode('Start Typing....'); 
    array_push($return_arr,$row_array); 
} 

$ret = array(); 
/* this is the return for a single result needed by select2 for initSelection */ 
if(isset($_GET['id'])) 
{ 
    $ret = $row_array; 
} 
/* this is the return for a multiple results needed by select2 
* Your results in select2 options needs to be data.result 
*/ 
else 
{ 
    $ret['results'] = $return_arr; 
} 
echo json_encode($ret); 

$db->close(); 

레거시 버전 : 내 예제에서 나는 오래된 YII 프로젝트를 사용하고 있습니다,하지만 당신은 쉽게 당신의 요구에 편집 할 수 있습니다.

요청은 JSON으로 인코딩됩니다.

public function actionSearchUser($query) { 
    $this->check(); 
    if ($query === '' || strlen($query) < 3) { 
     echo CJSON::encode(array('id' => -1)); 
    } else { 
     $users = User::model()->findAll(array('order' => 'userID', 
      'condition' => 'username LIKE :username', 
      'limit' => '5', 
      'params' => array(':username' => $query . '%') 
     )); 
     $data = array(); 
     foreach ($users as $user) { 
      $data[] = array(
       'id' => $user->userID, 
       'text' => $user->username, 
      ); 
     } 
     echo CJSON::encode($data); 
    } 

    Yii::app()->end(); 
} 

을 (당신은이 상점에 대한 YII이 필요하지 않습니다)보기에이 사용 :

$this->widget('ext.ESelect2.ESelect2', array(
'name' => 'userID', 
'options' => array(
    'minimumInputLength' => '3', 
    'width' => '348px', 
    'placeholder' => 'Select Person', 
    'ajax' => array(
     'url' => Yii::app()->controller->createUrl('API/searchUser'), 
     'dataType' => 'json', 
     'data' => 'js:function(term, page) { return {q: term }; }', 
     'results' => 'js:function(data) { return {results: data}; }', 
    ), 
), 

));

다음 스크립트는 공식 문서에서 가져

로 채택하는 것이 더 쉬울 수 있습니다

$("#e6").select2({ 
     placeholder: {title: "Search for a movie", id: ""}, 
     minimumInputLength: 1, 
     ajax: { // instead of writing the function to execute the request we use Select2's convenient helper 
      url: "http://api.rottentomatoes.com/api/public/v1.0/movies.json", 
      dataType: 'jsonp', 
      data: function (term, page) { 
       return { 
        q: term, // search term 
        page_limit: 10, 
        apikey: "ju6z9mjyajq2djue3gbvv26t" // please do not use so this example keeps working 
       }; 
      }, 
      results: function (data, page) { // parse the results into the format expected by Select2. 
       // since we are using custom formatting functions we do not need to alter remote JSON data 
       return {results: data.movies}; 
      } 
     }, 
     formatResult: movieFormatResult, // omitted for brevity, see the source of this page 
     formatSelection: movieFormatSelection // omitted for brevity, see the source of this page 
    }); 

이 여기에서 찾을 수 있습니다 : http://ivaynberg.github.io/select2/select-2.1.html

당신은 GitHub의 저장소에 선택 2의 사본을 optain 수 있습니다 위.