передача объекта json в массив — автозаполнение

#php #javascript #jquery #json

#php #javascript #jquery #json

Вопрос:

У меня есть два файла.

 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 автозаполнение просто не работает.

Ответ №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" );