如何从ajax数据创建jquery数组?

时间:2019-06-05 05:08:23

标签: php jquery arrays ajax

我想根据ajax响应创建数组。我从ajax获取数组,我必须为芯片创建动态数据 materializecss autocomplete

response from ajax

var tag = '';
$(document).on('keyup', '.tags', function() {

    var _this = $(this).val();

    if(_this.length > 1) {

        $.ajax({
            url: '/story/searchTags',
            type: 'POST',
            dataType: 'JSON',
            data: {
                tag: _this
            },
            success: function(tags) {
                tag = tags;
            }
        });

    }

});

$('.chips-placeholder').chips({
    placeholder: lang_('Your tag'),
    secondaryPlaceholder: '+ tag',
    autocompleteOptions: {
        // I need data like this from response
        data: {
           'Google', null
           'Googol', null
        },
        limit: 5,
        minLength: 2
    }
});
<div class="chips chips-placeholder chips-autocomplete input-field" style="background:#fff">
   <input class="input tags" placeholder="tag" autocomplete="off" />
</div>

that's my code

最后,感谢@Vel找到正确的答案。 jsfiddle - work code

1 个答案:

答案 0 :(得分:0)

您需要这样做。

var tag = '';
$(document).on('keyup', '.tags', function() {

    var _this = $(this).val();

    if(_this.length > 1) {

    /*$.ajax({
        url: '/story/searchTags',
        type: 'POST',
        dataType: 'JSON',
        data: {
        tag: _this
        },
        success: function(tags) {
        tag = tags;
        }
    });*/

    // ['google', 'googol'] <- this array I take from ajax
    tag = ['google', 'googol'];
    var obj = {};       

    $(tag).each(function (index, value) {       
        obj[value] = null;          
    });

    $('.chips').chips({
      secondaryPlaceholder: '+ tag',
      autocompleteOptions: {              
      data:obj,
      }
      });
    }

});

fiddle link