2

这个函数工作正常,但它只返回一个值。我在这里缺少什么?

这是我的代码:

  <script type='text/javascript'>
$(function () {

<?php
//Get the names and id's
$get_info=mysql_query("select * from table where id = '1'");

if($get_info){
while($row_info=mysql_fetch_array($get_info))
{
$username=$row_info['name'];
$user_id=$row_info['profile_id'];
?>


onDataRequest:function (mode, query, callback) {
 var data = [

{ id:<?php echo $user_id;?>, name:'<?php echo $username;?>', 'avatar':'http://cdn0.4dots.com/i/customavatars/avatar7112_1.gif', 'type':'contact' }

 ];

     data = _.filter(data, function(item) { return item.name.toLowerCase().indexOf(query.toLowerCase()) > -1 });
     callback.call(this, data);
    }
  });

<?php
}}
?>
});
</script>

预期结果:

{
    id: 295,
    name: 'Mike',
    'avatar': 'http: //cdn0.4dots.com/i/customavatars/avatar7112_1.gif',
    'type': 'contact'
},
{
    id: 296,
    name: 'John',
    'avatar': 'http: //cdn0.4dots.com/i/customavatars/avatar7112_1.gif',
    'type': 'contact'
}

实际输出:

{
    id: 295,
    name: 'Mike',
    'avatar': 'http: //cdn0.4dots.com/i/customavatars/avatar7112_1.gif',
    'type': 'contact'
}

它只返回 1 个项目。

4

2 回答 2

2

Every time you loop, you are assigning new values for your onDataRequest javascript function, however, it's the same function every time. You should think about execution order - first, you do PHP&MySQL server-side and what is generated as HTML or Javascript code there gets rendered and/or executed client-side later.

Basically, you have a PHP loop that goes over a set of values and those values are put inside a Javascript code that is within a HTML code block. So whatever you fetch from your database server last, is what is actually executed client-side.

The main idea here is that you shouldn't mix your server-side PHP code with client-side HTML or Javascript code.

于 2013-04-13T22:40:03.207 回答
2

您的数据库提取循环不会保留每个提取的值。您只需用当前 fetch 覆盖先前的 fetch 调用。也许你的意思是这样的:

while ($row_info = mysql_fetch_asssoc($result)) {
    $username[] = $row_info['name'];
    $user_id[] = $row_info['profile_id'];
}

vars 上的[]符号告诉 PHP 将 vars 视为数组并将新值推送到数组中。

然后,您可以使用以下命令将数组插入 javascript:

var usernames = <?php echo json_encode($username); ?>;
var user_ids = <?php echo json_encode($user_id); ?>;
于 2013-04-13T22:25:15.867 回答