javascript 创建的动态元素未POST

lf3rwulv  于 2023-03-21  发布在  Java
关注(0)|答案(4)|浏览(97)

我在用户从另一个select元素中进行选择后动态创建了一个HTML select元素,但是用于检查表单的PHP脚本无法识别新元素,并将其指示为null。
以下是片段:
some.js:

if(document.getElementById(firstselect).value=='somvalue'){
    document.getElementById(gamsDiv).removeChild(gamsElem);
    gamsElem = document.createElement("select");
    gamsElem.id = "FacilityGamsId";
    gamsElem.name = "FacilityGamsId";
   gamsElem.setAttribute("onChange", "updateHidden(this);makeUpdateRequest(arguments[0],this)");                    
    opt = document.createElement("option");
    opt.text="Select one ";
    opt.value=0;
    gamsElem.options.add(opt);
    .....some other stuff
    .....                           
    document.getElementById(gamsDiv).appendChild(gamsElem);

}

PHP脚本:

if($_POST){
    var_dump($_POST['FacilityGamsId'];
}

result: null

有什么原因导致服务器的post操作无法识别我的JS脚本中的任何动态HTML元素。如果我检查/检查新创建的元素,名称和id是完全相同的。

rnmwe5a2

rnmwe5a21#

它不会添加到存储在浏览器DOM中的表单中。
这个人也在做同样的事情:创建的动态元素未POST
一种解决方案是在服务器端构建动态表单--如果确实需要在客户端构建,我认为除了DOM之外,还需要操作表单(存储在document.forms中)。

yb3bgrhw

yb3bgrhw2#

此处:

gamsElem.options.add(opt);

add是select元素接口的一个方法,而不是options(它是一个HTMLElement集合,没有 add 方法)。所以:

gamsElem.add(opt);

解决问题的方法:Note that gamsElem.add(opt); does not work in Mozilla firefox 6 so I reverted to my old code of gamsElem.options.add(opt).
以及:

gamsElem.setAttribute("onChange",
 "updateHidden(this);makeUpdateRequest(arguments[0],this)");

会更好,因为:

gamsElem.onchange = function() {
    updateHidden(this);
    makeUpdateRequest(arguments[0], this);
};

虽然我不知道 arguments[0] 应该引用什么。
以下是通常的实现方式(尽管按钮会调用一个函数而不是一段内联代码,我这样做只是为了方便):

<form action="">
  <div id="div0">
    <select id="sel0" name="sel0">
      <option>option 0
    </select>
    <input type="submit">
  </div>
</form>

<button onclick="
  var div = document.getElementById('div0');
  var sel = document.getElementById('sel0');
  div.removeChild(sel);
  sel = document.createElement('select');
  sel.id = 'sel1';
  sel.name = 'sel1';
  sel.onchange = function(){alert(this.value);};
  sel.options[0] = new Option('Select one', '0');
  sel.options[1] = new Option('Select two', '1');
  div.appendChild(sel);
  ">Replace select</button>

需要第二个选项来触发 onchange 侦听器。
如果你想用一个元素替换另一个元素,创建一个新元素,然后替换旧的元素:

<button onclick="
  var oldSel = document.getElementById('sel0');
  var sel = document.createElement('select');
  sel.id = 'sel1';
  sel.name = 'sel1';
  sel.onchange = function(){alert(this.value);};
  sel.options[0] = new Option('Select one', '0');
  sel.options[1] = new Option('Select two', '1');
  oldSel.parentNode.replaceChild(sel, oldSel);
  ">Replace select</button>

或者你也可以替换这些选项(将select的options.length设置为零,然后添加新的选项)。

ars1skjm

ars1skjm3#

必须在FORM标记中添加新元素

c86crjj0

c86crjj04#

在DOM准备好之后运行这段代码,最好是jquery中的$.ready()。
并在div名称周围加上引号(“gamsDiv”)

相关问题