doulei6778 2014-04-25 01:34
浏览 114

Bootstrap Typeahead:从数据库获取数据为json

I'm having issues with getting bootstrap typeahead to return data as a json array from my MySQL database.

Here's what I have so far:

$('.typeahead').typeahead({
    items: 5,
    source: function (query, process) {
        $.ajax({
            url: 'typeahead.php',
            type: 'POST',
            dataType: 'JSON',
            data: 'query=' + query,
            success: function(data) {
                process(data);
            }
        });
    },
    highlighter: function(data) {
        // decode JSON data and return it here
    },
    updater: function(data) {
        console.log("CLICKED!");
    },
});

And here's the PHP file:

$search_for = $_POST['query'];
$return = array();

$stmt = $cxn->prepare('SELECT username, display_name FROM users WHERE username LIKE concat("%", ?, "%") OR display_name LIKE concat("%", ?, "%")');
$stmt->bind_param('ss', $search_for, $search_for);
$stmt->execute();
$result = $stmt->get_result();

while (($row = $result->fetch_assoc())) {
    array_push($return, array($row['username'], $row['display_name']));
}

$json = json_encode($return);
echo $json;

And here's the JSON it returns:

[["username","Display Name"],["username2","Display Name 2"]]

However, this code doesn't work when I test out the typeahead. It gives the following error in console:

http://i.imgur.com/xT8CV2b.png

So, my question is, how do you properly get multiple pieces of data from a database and put it into a json array?

  • 写回答

2条回答 默认 最新

  • drelgkxl93433 2014-04-25 08:38
    关注

    instead:

    while (($row = $result->fetch_assoc())) {
        array_push($return, array($row['username'], $row['display_name']));
    }
    

    use:

    while (($row = $result->fetch_assoc())) {
        if (isset($row)) $return[] = $row;
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站