简体   繁体   English

通过PHP中的$ _POST访问具有多个属性的选择选项

[英]Access select option with multiple attributes via $_POST in php

I am trying to extract the attributes in the options tag for a select element. 我正在尝试在select元素的options标记中提取属性。 The select element is dynamically loaded. select元素是动态加载的。

The specific form level code is as below: 具体的表单级别代码如下:

<form name='add'>
  Age: <select name='age[]'>
    <option value='1' stud_name='sre' st_address='address1'>23</option>
    <option value='2' stud_name='sam' st_address='address2'>24</option>
    <option value='5' stud_name='john' st_address='address13'>25</option>
  </select>
  <input type='submit' name='submit'/>
</form>

In my PHP file, I access the submitted data via: $_POST['age']; 在我的PHP文件中,我通过以下方式访问提交的数据: $_POST['age']; How can I get the other attributes and their value? 如何获得其他属性及其值?

The best way is to create individual input fields and control their value by Javascript while select is changed. 最好的方法是创建单个输入字段,并在更改select通过Javascript控制它们的值。

But if you persist to pass a multiple values by a single select , you may consider to use json , here an example: 但是,如果您坚持通过一次select传递多个值,则可以考虑使用json ,这里是一个示例:

HTML: HTML:

<form name="add">
  Age:
  <select name="age">
    <option value='{"age":"1","stud_name":"sre","st_address":"address1"}'>23</option>
    <option value='{"age":"2","stud_name":"sam","st_address":"address2"}'>24</option>
    <option value='{"age":"5","stud_name":"john","st_address":"address13"}'>25</option>
  </select>
  <input type="submit" name="submit"/>
</form>

PHP: PHP:

<?php

  $age = json_decode($_POST['age']);

?>

you can't access attribute values in php. 您无法在php中访问属性值。 only you can access is post data. 只有您可以访问的是发布数据。 If you want to access attributes in php, you have to use javascript or jQuery. 如果要访问php中的属性,则必须使用javascript或jQuery。

ex : https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_html_attr_set 例如: https : //www.w3schools.com/jquery/tryit.asp?filename=tryjquery_html_attr_set

same as above you can set values to post in a hidden field and submit to php 与上述相同,您可以设置值以在隐藏字段中发布并提交到php

You have missed the form's attribute; 您已经错过了表单的属性; method="post" in order to use $_POST in php. method =“ post”,以便在php中使用$ _POST。 Like: <form method="post" name="add"> ... </form> 就像: <form method="post" name="add"> ... </form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM