使用JavaScript和XMLHTTPRequest将FormData发布到php

rma*_*ues 0 html javascript php xmlhttprequest form-data

目前,我有两个文件,index.htm和accessdata.php。这是我在index.htm中拥有的:

<html>
<head>
<script>
function postData() {
  var xmlhttp=new XMLHttpRequest();
  var url = "accessdata.php";
  var checkBoxes_formData = new FormData(document.getElementById("checkBoxes"));

  xmlhttp.open("POST",url,true);
  xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
  xmlhttp.send(checkBoxes_formData);

  xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
      document.getElementById("result").innerHTML=xmlhttp.responseText;
    }
  }
}
</script>

</head>

<body>
<button type="button" onclick="postData()">POST</button>

<form id=checkBoxes>
<table>
    <tr><input type="checkbox" name="opt1" value="blue" checked> Blue</td>
    <tr><input type="checkbox" name="opt2" value="yellow"> Yellow</td> 
</table>
</form>

<p id="result"></p>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

这就是我在accessdata.php中拥有的内容:

<?php

$opt1=$_POST['opt1'];
echo $opt1;

echo "bla";
?>
Run Code Online (Sandbox Code Playgroud)

从今起

<p id="result"></p>
Run Code Online (Sandbox Code Playgroud)

显示“ bla”,但不显示“ blue”或“ yellow”。

我究竟做错了什么?

正确的HTML代码如下!

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>POST PHP XMLHTTPRequest</title>
<script>
function postData() {
  var xmlhttp=new XMLHttpRequest();
  var url = "accessdata.php";
  var checkBoxes_formData = new FormData(document.getElementById("checkBoxes"));

  xmlhttp.open("POST",url,true);
  xmlhttp.send(checkBoxes_formData);

  xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
      document.getElementById("result").innerHTML=xmlhttp.responseText;
    }
  }
}
</script>

</head>

<body>
<button type="button" onclick="postData()">POST</button>

<form id="checkBoxes">
<input type="checkbox" name="opt1" value="blue"> Blue
<input type="checkbox" name="opt2" value="yellow" checked> Yellow

</form>

<p id="result"></p>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

Que*_*tin 7

blue 没有显示,因为您声称:

xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
Run Code Online (Sandbox Code Playgroud)

但是FormData对象将数据编码为multipart/form-data

删除明确设置内容类型的代码,然后让浏览器为您生成它。(不要尝试将其显式设置为multipart/form-data,您也必须指定边界标记将在标头中显示)。

yellow 由于相同的原因而没有出现,也是因为:

  • 您只在查看,opt1它与名称opt2
  • 复选框控件只有在被选中时才成功(即,将存在于提交的数据中)(默认情况下,黄色复选框未选中)。

更麻烦的是,您的HTML无效。使用验证器。您不能将输入作为表行的子级,您需要在它们之间创建一个表数据单元格。(请注意,您似乎正在尝试使用表格进行布局,因此您可能应该完全删除表格)。