将隐藏的输入值获取到$ _POST

时间:2018-11-19 02:02:56

标签: php superglobals

我已在表单中分配了一个隐藏的输入,该输入将存储选中的复选框的值(如该图所示,该部分工作正常):

enter image description here

此隐藏输入的值将转换为字符串,以便稍后对其执行爆炸。

当我尝试通过var_dump(['distribution'])在PHP中访问它时,我得到了以下数据:string(0) ""

php端的代码:

if(isset($_POST['distribution'])){
  var_dump($_POST['distribution']);
  die;
}

以防万一,这是我的html: <input type="hidden" name="distribution[]" />

这是我的JS:

function isChecked(){
    let distributionEL = document.querySelector("[name='distribution[]']");
    console.log(distributionEL.value);
    sendingLists.forEach(function(list) {
      let sendSMSArr = distributionEL.value.split(',');
        if(list.checked == true){
          sendSMSArr.push(list.value);
        } else {
          let index = sendSMSArr.indexOf(list.value)
          if (index > -1) {
            sendSMSArr.splice(index, 1);
          }
      }
      distributionEL.value = sendSMSArr.join(',');
  });
}

更新

在创建输入及其工作时,我使用了name='distribution[]',但是, 当有人使用根据查询创建复选框的搜索栏时,它不会累积前搜索和后搜索的值。

我的ajax:

const resToHtml = res => {
// create a virtual fragment where we will create all the HTML in
let resultDiv = document.createElement('div');

// iterates on each option
res.forEach(({
sendingListName,
sendingListID
}) => {

// create an <li>
let liEl = document.createElement('li');


// create a <span> and an <input>
let spanEl = document.createElement('span');
let inputEl = document.createElement('input');

// create class attribute and append it to input
let elementClass = document.createAttribute("class");
let nameClass = document.createAttribute("name");
elementClass.value = "sending-lists"; 
nameClass.value = "distribution[]"; 
inputEl.setAttributeNode(elementClass);
inputEl.setAttributeNode(nameClass);

    // the <span> will hold the visible text
    spanEl.textContent = sendingListName;

    // the <input> will be a checkbox with a value
inputEl.type = "checkbox";
inputEl.value = sendingListID;
inputEl.name = 'distribution[]';



// put the <input> and the <span> inside the <div>
liEl.appendChild(inputEl);
liEl.appendChild(spanEl);

    // add the <li> into the <div>
resultDiv.appendChild(liEl);
})

// apply all the elements into the <div>
listREl.innerHTML = '';
listREl.innerHTML = resultDiv.innerHTML;
}

1 个答案:

答案 0 :(得分:1)

如果使用正确的命名,而只可以在PHP中以数组形式访问它们,为什么要使用JS附加值并存储为字符串呢?

<form name="demo" method="POST" action="<?php print($_SERVER['PHP_SELF']); ?>">
<input type=checkbox name="checkbox[]" value="val1"> check 1<br />
<input type=checkbox name="checkbox[]" value="val2"> check 2<br />
<input type=checkbox name="checkbox[]" value="val3"> check 3<br />
<input type=submit name=submit value="submit">
</form>

然后在PHP中,您可以访问值:

<?php

  print("Selected checkbox values were: ".implode(",",$_POST['checkbox']))."<br />");

?>