php - Select2 jQuery 与 JSON MySQL

标签 php jquery mysql json jquery-select2

我为此挠头了一段时间,最后决定寻求帮助,我尝试使用以下代码复制 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 返回添加 header 的问题,我使用开发者工具并观察 jQuery 响应发现了该问题:)

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

相关文章:

jquery - 第一次鼠标调用 JQuery 的 .show() 不显示动画

mysql - 在 asp.net 中显示表中的记录时出现一些问题

php - 使用html php POST选中和未选中的复选框

javascript - JQuery 表单提交不验证字段

javascript - Stripe 付款问题 - 网络错误,您尚未被收取费用

javascript - 仅显示一个 DIV 在具有相同类 jQuery 的单击事件上打开

jquery - 空哈希和无哈希的区别

mysql - MySQL通配符字符串选择

javascript - 登录代码在 Internet Explorer 中不起作用,但在 Chrome 和 Firefox 中起作用

php - 如何在 PHP 中用 'different' 替换 'normal'?