1、发送的信息不在URL中,而是在xhr.send();里面,即:
xhr.send("username="+username+"&sex="+sex);
并且要设置请求头,即:
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
php文件里面在接受的时候,要写成post方式,即:
$username = $_POST["username"];
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form action="doGet.php" method="GET">
<p>
姓名:<input type="text" name="username" id="username">
</p>
<p>
性别:
<input type="radio" name=
"sex" value="男" id="nan" checked/>男
<input type="radio" id="nv" name="sex" value="男" />女
</p>
<p>
爱好:
<input type="checkbox" name="hobby" id="" value="足球">足球
<input type="checkbox" name="hobby" id="" value="篮球">篮球
<input type="checkbox" name="hobby" id="" value="羽毛球">羽毛球
</p>
<p>
你的留言
<textarea name="liuyan" rows="10" cols="30"></textarea>
</p>
<p>
<input type="button" id="btn" value="点我提交">
</p>
</form>
<div></div>
<script type="text/javascript">
var btn = document.getElementById("btn");
btn.onclick = function() {
var username = document.getElementById("username").value;
var sex = document.getElementById("nan").checked?"男":"女";
// 创建对象
var xhr = getXMLHTTPRequest();
// 准备请求动作
xhr.open("post","doPost.php",true);
//让AJAX 以提交表单的方式发起post的ajax请求
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
// 发送
xhr.send("username="+username+"&sex="+sex);
// 回调
xhr.onreadystatechange = function() {
//console.log("状态"+xhr.readyState);
if(xhr.readyState == 4) {
if(xhr.status == 200) {
console.log(xhr.responseText);
}
}
}
}
function getXMLHTTPRequest() {
if(window.XMLHttpRequest) {
return new XMLHttpRequest();
} else {
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
</script>
</body>
</html>
php:
<?php
// 得到姓名
$username = $_POST["username"];
// 得到sex
$sex = $_POST["sex"];
echo "已经收到".$username.$sex;
?>