我已经为此花了一段时间,终于决定寻求帮助,我尝试使用下面的代码复制JSON的Select2教程,因为我们正在运行PHP 5.1(它是一个旧平台)必须添加一个函数来手动创建JSON。

任何协助获得这项工作将不胜感激

测试HTML

<style>
    #wgtmsr{
        width:150px;
    }

</style>

<h1>IRBs</h1>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet" />
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.full.js"></script>
<form>
<select class="js-irb" multiple="multiple" id="wgtmsr"></select>
</form>
<script type="text/javascript">
    jQuery.noConflict();
    function formatIRB (data) {
        if (data.loading) return data.text;

        var markup = '<p>' + data.text + '</p>';

        return markup;
    }

    function formatSelection (data) {
        return data.id || data.text;
    }

    jQuery(document).ready(function() {
        jQuery(".js-irb").select2({
            ajax: {
                url: "ajax/irb",
                dataType: 'json',
                delay: 250,
                data: function (params) {
                    return {
                        q: params.term// search term
                    };
                },
                processResults: function (data) {
                    // parse the results into the format expected by Select2.
                    // since we are using custom formatting functions we do not need to
                    // alter the remote JSON data
                    return {
                        results: data
                    };
                },
                cache: true
            },
            escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
            minimumInputLength: -1,
            templateResult: formatIRB, // omitted for brevity, see the source of this page
            templateSelection: formatSelection // omitted for brevity, see the source of this page
        });
    });
</script>


测试JSON

<?php
/**
 * Supplementary json_encode in case php version is < 5.2 (taken from http://gr.php.net/json_encode)
 */
if (!function_exists('json_encode'))
{
    function json_encode($a=false)
    {
        if (is_null($a)) return 'null';
        if ($a === false) return 'false';
        if ($a === true) return 'true';
        if (is_scalar($a))
        {
            if (is_float($a))
            {
                // Always use "." for floats.
                return floatval(str_replace(",", ".", strval($a)));
            }

            if (is_string($a))
            {
                static $jsonReplaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"'));
                return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"';
            }
            else
                return $a;
        }
        $isList = true;
        for ($i = 0, reset($a); $i < count($a); $i++, next($a))
        {
            if (key($a) !== $i)
            {
                $isList = false;
                break;
            }
        }
        $result = array();
        if ($isList)
        {
            foreach ($a as $v) $result[] = json_encode($v);
            return '[' . join(',', $result) . ']';
        }
        else
        {
            foreach ($a as $k => $v) $result[] = json_encode($k).':'.json_encode($v);
            return '{' . join(',', $result) . '}';
        }
    }
}
$db = Database::GetConnection('default');

#$result = $db->Query("SELECT i.ID,i.IRBNO, i.Name AS irbName FROM irb i WHERE irbName LIKE '%".strtoupper($_GET['q'])."%' or '%".($_GET['q'])."%'");
$result = $db->Query("SELECT ID,IRBNO, Name FROM irb WHERE Name LIKE ? OR IRBNO LIKE ? ORDER BY IRBNO ASC LIMIT 0,4", 'ss','%' . $_GET['q'] . '%','%' . $_GET['q'] . '%');

if(count($result) > 0){
    foreach($result as $row){
    //while($row = $result->fetch_array()) {
        //$answer[] = array("id"=>$row['ID'], "text"=>$row['Name']);
        $answer[] = array("id"=>$row['ID'],"text"=>$row['IRBNO']." - ".$row['Name']);         // the text I want to show is in the form of option id - option
    }
}else {
    $answer[] = array("id"=>"0", "text"=>"No Results Found...");
}
echo json_encode($answer);
?>


JSON返回

[{"id":1,"text":"1 - TEST IRB"},{"id":2,"text":"1 - TEST IRB2"}]

最佳答案

好的,这是网站代码向JSON返回中添加标头的问题,我使用developertools查看了jQuery响应后发现了问题:)

关于php - 带有JSON MySQL的Select2 jQuery,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31783651/

10-08 20:41