【问题标题】:pass json object to array - autocomplete将 json 对象传递给数组 - 自动完成
【发布时间】:2011-10-10 17:09:26
【问题描述】:

我有两个文件。

location.php, that outputs this:

[["javascript"],["PHP"]] 

在另一个文件中:

<script type="text/javascript">
$.getJSON('location.php', function(data) {
      var sampleTags = [];

      $.each(data, function(key, val) {
         sampleTags.push(val);
         });

         alert(sampleTags); // show javascript, php


        //-------------------------------
        // Preloading data in markup
        //-------------------------------
        $('#myULTags').tagit({
            availableTags : sampleTags, // this param is of course optional. it's for autocomplete.
            // configure the name of the input field (will be submitted with form), default: item[tags]
            itemName : 'item',
            fieldName : 'tags'
        });
    });
</script>

自动完成不起作用。为什么?

如果我使用:

var sampleTags = [ 'javascript', 'php'];

一切正常,但使用 json 时,自动完成功能根本不起作用。

【问题讨论】:

    标签: php javascript jquery json


    【解决方案1】:
    $.each(data, function(key, val) {
      sampleTags.push(val[0]);
    });
    

    应该将 [["foo"],["bar"]] 减少为 ["foo", "bar"]

    【讨论】:

      【解决方案2】:
      [["javascript"], ["PHP"]]
      

      是一个二维数组。您的 Javascript 需要一个一维数组。有你的 PHP 输出:

      [ "javascript", "PHP" ]
      

      在 PHP 中,数组应如下所示:

      array( "javascript", "php" );
      

      【讨论】:

        猜你喜欢
        • 2015-05-10
        • 2019-03-31
        • 2011-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多