如何将 select2 数组输出转换为单个字符串?

如何将select2数组输出转换为单个字符串(以逗号分隔)?就像这样"task_owner":"Administrator,abc2"。当前输出用逗号分隔,但在单个数组中"task_owner":["Administrator","abc2"]。这是因为数据库是通过字符串而不是数组接收的。

另一个问题,如何重新转换回数组,因为在编辑过程中,Ajax 将从数据库发送该字符串,我可能需要转换回数组以用于显示目的。

我被提到了这个链接但不起作用。

<form id="myForm">

    <select type="text" class="form-control myClass" id="myID" multiple="multiple"></select>

</form>


$('.myClass').select2({

    tags: true

 });    


$('#btnSubmit').on('click',function(){

    var testOutput = "";   // I put this because an error appear so I create a new var but the output is = "null", why?

    var owner = $('#myID').val();


    if (owner.val() !== null && owner.val().length > 0){

        var testOutput = $('#myID') = owner.val().join(',');

        testOutput = Object.assign({}, {task_owner: testOutput.task_owner.join(",")})

    }


    // parameter that need to send to API

    var obj = {

        task_owner : testOutput,

        // Another parameter...

    };

    var params = JSON.stringify(obj);


    $.ajax({

        // My Ajax Condition...

    });

});


繁花如伊
浏览 100回答 1
1回答

ABOUTYOU

正如所讨论的:$(".myClass").select2({&nbsp; tags: true});$("#btnSubmit").on("click", function() {&nbsp; var testOutput = ""; // I put this because an error appear so I create a new var but the output is = "null", why?&nbsp; var owner = $("#myID").val(); //&nbsp; if (Array.isArray(owner) && owner.length) {&nbsp; &nbsp; testOutput = owner.join(",");&nbsp; }&nbsp; var obj = {&nbsp; &nbsp; task_owner: testOutput&nbsp; };&nbsp; var params = JSON.stringify(obj);&nbsp; $.ajax({&nbsp; &nbsp; // My Ajax Condition...&nbsp; });});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5