如何在PHP中通过父类名获取元素

时间:2016-01-24 13:25:17

标签: php

HTML标记:

<form>
  <div class="required">
    <input id="name" name="name">
  </div>
  <div class="required">
    <input id="email" name="email">
  </div>
  <div class="non-required">
    <input id="other" name="other">
  </div>
  ...
  alot of input here
  ...

</form>

PHP:

<?php

extract($_POST, EXTR_PREFIX_ALL, 'input');

if (empty($input_name) || empty($input_email) || empty($input_other) || ... alot of input here...) { // i want only the input that has `required` class in this line
  // main function here
}

?>

我可以手动编辑它但是如何自动为PHP主函数选择inputrequired

感谢。

2 个答案:

答案 0 :(得分:2)

您无法访问父级的班级名称。当用户提交表单时,不会传输此信息。

$ _POST中唯一可用的信息是input元素的名称和值。您可以定义输入元素的名称以表示必需/非必需,如:

<form>
    <div class="required">
         <input id="name" name="required[name]">
    </div>
    <div class="required">
         <input id="email" name="required[email]">
    </div>
    <div class="optional">
         <input id="another" name="optional[another]">
    </div>
    <div class="required">
         <input id="other" name="required[other]">
    </div>
</form>

使用此架构,您将在$ _POST中有两个子数组,名为必需和可选:

Array //$_POST
(
     [required] => Array
     (
         [name] => value,
         [email] => value,
         [name] => value
     ),
     [optional] => Array
     (
         [another] => value
     )
)

警告
如果您使用此解决方案,请确保您正确验证输入。您将信任用户代理以提供有关字段的正确信息。看看Trincot对纯服务器端解决方案的回答。

答案 1 :(得分:2)

由于您自己生成HTML,实际上您知道哪些输入元素具有类“required”。所以我建议你先创建一个包含必填字段的数组,然后用动态类值生成HTML。

然后你可以使用相同的数组来检查空虚:

HTML生成:

<?php
// define the list of required inputs:
$required = array("name", "email");

// define a function that returns "required" or "non-required" 
// based on the above array.
function req($name) {
    global $required;
    return in_array($required, $name) ? 'required' : 'non-required';
}
// Now generate the classes dynamically, based on the above:
?>
<form>
  <div class="<?=req('name')?>">
    <input id="name" name="name">
  </div>
  <div class="<?=req('email')?>">
    <input id="email" name="email">
  </div>
  <div class="<?=req('other')?>">
    <input id="other" name="other">
  </div>
  ...
  alot of input here
  ...

</form> 

然后在处理输入时,再次使用上述功能:

<?php

// This extract is not needed for the next loop, but you might need it still:
extract($_POST, EXTR_PREFIX_ALL, 'input');

// go through all inputs that are required and test for empty
// until you find one, and produce the appropriate response 
foreach($required as $name) {
    if (empty($_POST[$name])) {
        // main (error?) function here
        break; // no need to continue the loop as we already found an empty one
    }
}

?>