在PHP / Javascript中自动填充表单

时间:2014-10-04 19:05:12

标签: javascript php ajax mysqli autocomplete

我一直在尝试制作一整天的自动完成脚本,但我似乎无法弄明白。

<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。 我想要做的是使用ajax自动完成第一个字段 像这样:preview

当第一个输入中有9个数字时,它会使用正确的链接数据填充其他输入

ajax.php上的脚本向服务器发送mysqli_query并要求所有    data(table:fields || rows:number,first,sec,third)

1 个答案:

答案 0 :(得分: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编码。 (你不需要yii这个)

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();
}

在视图中使用它:

$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存储库中获取select2的副本。