简体   繁体   English

自动完成的数组不显示任何内容

[英]Array in autocomplete not showing anything

Here is my code for jQuery autocomplete: 这是我的jQuery自动完成代码:

PHP Code: PHP代码:

$query = "SELECT * FROM users";
$users = db::getRecords($query);

$usernames = Array();
foreach ($users as $user) 
{
    $username[] = '"'.$user['username'].'"';
}

Array is associative. 数组是关联的。

JS: JS:

$("#username").autocomplete({

    source: [<?php  echo join(',', $usernames); ?>],   
    select: function(event, ui) {

    }
});

This array $user is not getting converted into JavaScript array. $user这个数组未转换为JavaScript数组。 Nothing happens when I type in my username input. 当我输入用户名输入时,没有任何反应。 How to define the source with PHP array? 如何用PHP数组定义源?

I suggest you do it this way if you're in the same page. 如果您在同一页面上,建议您使用这种方式。

In PHP: 在PHP中:

$username = array();
$query = "SELECT * FROM users";
$users = db::getRecords($query);
foreach ($users as $user) {
    $username[] = array('id' => $user['id'], 'username' => $user['username'], 'label' => $user['username']);
}

$username = json_encode($username);

Then on JS: 然后在JS上:

$("#username").autocomplete({
    source: <?php echo $username; ?>,   
    select: function(event, ui) {
        alert(ui.item.id); // alets that user id
    }
});

But it strongly suggest separate the PHP, so that you'll only need to use echo json_encode($data) in that PHP. 但是它强烈建议将PHP分开,这样您只需要在该PHP中使用echo json_encode($data)

Then use the php path to the source: 'path/to/phpfile.php' . 然后使用source: 'path/to/phpfile.php'的php路径source: 'path/to/phpfile.php'

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

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