简体   繁体   中英

jquery select2 - Format the results via AJAX php

i use select2, i want to format my results like

, first. ,第一。

$("#id").select2({
    minimumInputLength : 0,
    allowClear: true,
    ajax : {
        url : "Form/page.php",
        dataType : 'json',
        data : function (term, page) {
            return {
                q : term
            };
        },
        results: function (data, page) {
            return { results : data.ex};
        },
        formatResult :  function formatResult(ex) {
            return '<b>' + ex.name + '</b>';
        }
    }

});

my php file like

    while($r=mysql_fetch_array($m)) {
        $rows['id']=$r['id'];
        $rows['text']=$r['name'];
        $rows['first']=", ". $r['first'];
        $rows2[]=$rows;
    }
    print json_encode($rows2);

how can i do that, thanks

I think the php code has to be like this:

while($r=mysql_fetch_array($m)) {
    $rows['id']=$r['id'];
    $rows['name']=$r['name'];
    $rows['first']=$r['first'];
    $rows2[]=$rows;
}
print json_encode($rows2);

So, you pass an array of json objects with an id, name and first.

Change the return of formatResult to:

return '<b>' + ex.name + '</b>, ' + ex.first;

PHP example reposted from the Select2 - source example:

https://github.com/ivaynberg/select2/wiki/PHP-Example

In JS:

$('#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);

            });
        }

    });

and in PHP:

<?php 
    $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();
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM