将选择框的选定值作为字符串发送到PHP [英] send selected values of select box to PHP as string

查看:73
本文介绍了将选择框的选定值作为字符串发送到PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Select2 3.4.5 创建选择框,

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>

要在php中获取选择框的多个选定值,我必须通过 name ="mydata []" 来修改 name ="mydata" PHP 我通过以下代码获取值:

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/>";
}

?>

但是我的问题是:如何将选择框的选定值作为 string 发送到PHP以像这样在PHP中恢复:'D1,D2,D3',以及谢谢.

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.

我想以字符串形式发送数据,而不是以数组形式接收数据将其更改为字符串

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

推荐答案

使用PHP的服务器端

理想情况下,一旦发送值,您将使用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']);

其中 $ _ POST ['mydata'] 是数组

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

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

使用jQuery的客户端

您的标题为将选择框的选定值作为字符串发送到PHP".您可以在JS中通过捕获表单的Submit事件并使用.join()更改该字段的值.

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(','));
});

您的表单(未提供)将需要一个ID < form id ="formid" ...>

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

这篇关于将选择框的选定值作为字符串发送到PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆