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条)

报告相同问题?

悬赏问题

  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,