【问题标题】:jquery tokeninput : how to pass a dynamic array for autocompletionjquery tokeninput:如何传递动态数组以进行自动完成
【发布时间】:2015-01-13 22:14:27
【问题描述】:

使用 tokenInput,我的自动完成没有返回任何内容,我找不到原因。

首先我对数据库进行查询以查找已连接用户的所有联系人。

我得到一个数组,例如:

$contacts = Array( [0] => Array ( [id] => 1 [name] => John ) [1] => Array ( [id] => 3 [name] => Peter ) )

然后我使用 http_build_query 因为我想通过 URL 传递数组:

$contacts_url =http_build_query($contacts);

返回:

print_r($contacts_url)= 0%5Bid%5D=1&0%5Bname%5D=John&1%5Bid%5D=3&1%5Bname%5D=Peter

然后我使用 tokenInputs,并通过 url 发送我的数组:

$(document).ready(function () {
    $("#my-text-input").tokenInput("<?php echo $this->webroot.'populate.php?'.$contacts_url ?>", {theme: "facebook"});
});

populate.php 页面包含:

<?php
    header('Content-type: text/javascript');
    $a= $_GET;
    $json_string = json_encode($a);
    echo $json_string;
?>

如果我打开 php 页面 ../populate.php?0%5Bid%5D=1&0%5Bname%5D=John&1%5Bid%5D=3&1%5Bname%5D=Peter 我明白了:

[{"id":"1","name":"John"},{"id":"3","name":"Peter"}]

我觉得不错

但是自动补全什么也没返回:(

非常感谢任何帮助!

非常感谢

【问题讨论】:

  • 您的搜索参数也作为 get 变量发送,我想这会弄乱您的 json_encode。您是否尝试过使用 Chrome 的网络工具之类的工具来查看您在输入字符时从服务器得到什么响应?如果您可以进行现场演示,那将非常有助于了解正在发生的事情。
  • 另外,您从 PHP 发送所有联系人,打印到 Javascript,然后再次发送回 PHP 是否有特殊原因?这是一种奇怪的做法!如果这就是你所做的一切,我根本不明白你为什么要从服务器请求,而不是打印到本地 JSON 数组 - jQuery TokenInput 也适用于此。
  • 非常感谢克里斯!!
  • 你是对的两次!我的网址很乱,在通过 tokeninput() 后,它将 % 更改为 %25 并在末尾添加了 &q=a 。但是您的第二条评论非常有价值!我删除了这个 php 文件并做了 $json_string = json_encode($contacts);
  • 现在一切正常。非常感谢您的帮助!

标签: jquery-plugins jquery-tokeninput


【解决方案1】:

默认情况下,搜索参数也作为 $GET 变量发送,我想这会弄乱您的 JSON 编码。

更好的方法是在本地进行,如下所示:

$(document).ready(function () {
    $("#my-text-input").tokenInput("<?php echo json_encode($contacts) ?>", {theme: "facebook"});
});

【讨论】:

    【解决方案2】:
    $(document).ready(function() {
                $("#searchword").tokenInput(            
    
        /* Given that $json_res = json_encode($user_arr); in the PHP. 
    Using <?php echo $json_res ?> OR <?php echo json_encode($user_arr) ?> without quotes and blocks gives the same result. 
    
        The other way is to define var ar =<?php echo $json_res?>; in JS and pass it as .tokenInput(ar, {} */
    
                   <?php echo $json_res ?>
                , {
                    propertyToSearch: "username",
                    theme: "facebook",
                    preventDuplicates: true,
                    excludeCurrent: true                    
                });
        });      
    

    // 如果 JSON 文件有 [{"id":"856","product":"sample1"}, {"id":"1035","product":"sample product 2"}],执行以下:

    $('#product_tokens').tokenInput('/products.json', { propertyToSearch: 'product' });
    

    【讨论】:

    • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。
    猜你喜欢
    • 2011-08-20
    • 2012-04-16
    • 2017-10-23
    • 1970-01-01
    • 1970-01-01
    • 2011-05-20
    • 2013-09-12
    • 2011-01-08
    • 1970-01-01
    相关资源
    最近更新 更多