简体   繁体   English

带有JSON MySQL的Select2 jQuery

[英]Select2 jQuery with JSON MySQL

I've been scratching my head for a while with this and have finally decided to ask for assistance, I am trying to duplicate the Select2 tutorial for JSON with the below code, as we are running PHP 5.1 (its an old platform) I have had to add a function to create the JSON manually. 我已经为此花了一段时间,终于决定寻求帮助,我尝试使用以下代码复制JSON的Select2教程,因为我们正在运行PHP 5.1(它是一个旧平台)必须添加一个函数来手动创建JSON。

Any assistance getting this working would be appreciated 任何协助使这项工作,将不胜感激

TEST HTML 测试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>

TEST JSON 测试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 RETURN JSON返回

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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