<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
window.onload = function(){
var btn = document.getElementById("btn");
btn.onclick = function(){
var xhr = null;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var username = document.getElementById("username").value;
var password = document.getElementById('password').value;
var url = "post.php";
xhr.open('post',url,true);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
var param = 'username='+username+'&password='+password;
alert(param)
xhr.send(param);
xhr.onreadystatechange = function(){
if(xhr.readyState==4){
if(xhr.status==200){
var data = xhr.responseText;
console.log(data);
document.getElementById("content").innerHTML = data;
}
}
}
}
}
</script>
</head>
<body>
<form>
用户名: <input type="text" id="username"/>
密码: <input type="password" id="password"/>
<input type="button" value="提交" id="btn"/>
</form>
<div id="content"></div>
</body>
</html>
这是 php 文档
<?php
header("Content-Type:text/html;charset=utf-8");
//$username = $_GET["username"];
//$password = $_GET["password"];
$username = $_POST['username'];
$password = $_POST['password'];
echo "用户名:".$username."密码:".$password;
?>
2 个解决方案
#1
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded ;charset=utf-8");
去掉红色的内容试试,不过就算content-type错,也不会把参数加到url上的,检查你的服务器是不是做了什么转换
Web开发学习资料推荐
ajax对象属性withCredentials
javascript生成二维码
#2
#1
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded ;charset=utf-8");
去掉红色的内容试试,不过就算content-type错,也不会把参数加到url上的,检查你的服务器是不是做了什么转换
Web开发学习资料推荐
ajax对象属性withCredentials
javascript生成二维码