如何将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... });});
1 回答
ABOUTYOU
TA贡献1812条经验 获得超5个赞
正如所讨论的:
$(".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 (Array.isArray(owner) && owner.length) {
testOutput = owner.join(",");
}
var obj = {
task_owner: testOutput
};
var params = JSON.stringify(obj);
$.ajax({
// My Ajax Condition...
});
});
- 1 回答
- 0 关注
- 99 浏览
添加回答
举报
0/150
提交
取消