duancheng7743 2013-11-16 18:51
浏览 230
已采纳

Select2 - >动态输入以字符串形式返回(jQuery

The format for my select 2 is as such:

$("#selectPretty").select2({
    tokenSeparators: [","], 
    tags:["1", "2", "3", "php", "tiger", "test", "big bang theory", "bikes", "gh", "sd", "cheese", "food", "name", "jack", "chickens", "yikes!", "testing", "this", "is", "a", "questionj", "new", "question", "s"]
});

Which shows as such:

enter image description here

BUT, when I try to assign data into the box dynamically through AJAX by using this code:

$.ajax({
    type: "POST",
    url: "grabTags.php",
    data: "tags="+$("#selectPretty").val(),
    success: 
        function(msg2) {
            alert(msg2);
            $("#selectPretty").select2({
                tokenSeparators: [","],
                tags:[msg2]
            });
        }
});

It will come out like so:

enter image description here

For some reason the whole string is one option and I can't make it explode the result into different options...

Does anyone know what I can do here?

Note that 'tags:[msg2]' is returned from my grabTags.php file and 'msg2' = "1", "2", "3, etc...

Kindest Regards

  • 写回答

2条回答 默认 最新

  • douwen7475 2013-11-16 20:22
    关注

    Have you tried splitting the string that comes back from the PHP?

    You can invoke the split method on a string (such as that which is returned from your PHP) and pass it a separator (in your case a ,).

    Something like this should work:

    $.ajax({
        type: "POST",
        url: "grabTags.php",
        data: "tags="+$("#selectPretty").val(),
        success: 
            function(msg2) {
                //at this point, msg2 is the string: '"1","2","3"'
    
                var myTags = msg2.split(',');
                //myTags is now the array: ["1","2","3"]
    
                $("#selectPretty").select2({
    
                    //tags needs to be an array, so pass in myTags
                    tags: myTags 
                });
            }
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算