【发布时间】:2015-09-15 03:17:00
【问题描述】:
目前我有两个文件,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>
这就是我在 accessdata.php 中的内容:
<?php
$opt1=$_POST['opt1'];
echo $opt1;
echo "bla";
?>
现在开始
<p id="result"></p>
“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>
【问题讨论】:
-
用 关闭表单
-
好的,已经这样做了,我在构建示例代码时的错误,仍然无法正常工作。
-
我从未使用过FormData,但似乎您不应该设置内容类型。无论如何,检查返回的 FormData 是什么形式。我将开始回显整个 $_POST 数据。但在您可以
console.log(checkboxes_formData)之前,这通常有助于了解发生了什么。
标签: javascript php html xmlhttprequest form-data