douzhanlie9209 2013-12-27 13:52
浏览 22
已采纳

将选择框的选定值作为字符串发送给PHP

I'm using Select2 3.4.5 for create select boxes,

I use this code for creatre a Multi-Value Select Boxe and everything is fine.

<select id="e1" name="mydata" multiple>
  <option value="D1">Data1</option>
  <option value="D2">Data2</option>
  <option value="D3">Data3</option>
</select>

...

<script>
     $("#e1").select2();
</script>

For get multiple selected values of select box in php I have to modify name="mydata" by name="mydata[]", and in PHP I get values by this code:

<?php
foreach ($_POST['mydata'] as $names) {
    print "You are selected $names<br/>";
}

?>

But my question: How can I send selected values of select box to PHP as string to recover in php like this : 'D1,D2,D3' , and thanks.

Edit:

I want to send the data as string, not receive it as an array then change it as string

  • 写回答

3条回答 默认 最新

  • dousi6701 2013-12-27 13:57
    关注

    Server-side with PHP

    Ideally you would do this with PHP once the value is sent. To convert the selected items just want to implode the array

    $names=implode(',', $_POST['mydata']);
    

    Where $_POST['mydata'] is an array

    [0]=>'D1',
    [1]=>'D2',
    [2]=>'D3'
    

    implode(',', $_POST['mydata']) would be 'D1,D2,D3'

    Client-side with jQuery

    Your title says "send selected values of select box to PHP as string". You would do that in JS by catching the submit event of the form and using .join() to change the value of that field.

    $('#formid').on('submit', function(){
        $('#e1').val($('#e1').val().join(','));
    });
    

    Your form (not given) would need an id <form id="formid" ...>

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失