duancheng7743
duancheng7743
2013-11-16 18:51

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 douwen7475 8年前

    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 
                });
            }
    });
    
    点赞 评论 复制链接分享
  • dssqq82402 dssqq82402 8年前

    The Select2 tags need a javascript array, not just a string surrounded by brackets.

    So server side, have PHP spit out a json encoded array:

    $tags = array("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");
    echo json_encode($tags);
    

    Now client side take that response in your ajax success handler, and assign it directly to tags.

    Note that you may need to set dataType to json in your ajax call so that jQuery automatically parses the response as json. Not sure if it will figure that out on its own or not.

    You may also be able to get rid of tokenSeparators if you provide an actual array as your tags.

    点赞 评论 复制链接分享

为你推荐