<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
function clickH(){
var http=new XMLHttpRequest();
http.open("post","ajax",true); //对应参数:请求方式 ,请求(这里是servlet资源) ,true代表异步
/*application/x-www-form-urlencoded表示客户端提交给服务器文本内容的编码方式 是URL编码,
即除了标准字符外,每字节以双字节16进制前加个“%”表示,如果没setRequestHeader()收不到值*/
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
http.send("username=admin");
http.onreadystatechange=function (){
if (http.readyState==4&&http.status==200){
document.getElementById("myDiv").innerText=http.responseText;
}
}
}
</script>
</head>
<body>
<h2 id="myDiv">这是个什么内容</h2>
<button type="button" onclick="clickH()">点下试试,试试就试试</button>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script>
//如果收不到值,考虑没加"Content-type","application/x-www-form-urlencoded");
//而且success为成功发送接收请求后的回调函数,function括号里的aa可以随便写,只是个参数,但是它代表请求url后,servlet返回的文本。
function clickHe(){
$.ajax({
type: "POST",
url: "ajax",
data: "username=Boston",
success: function(aa){
alert( aa );
}
})
}
</script>
</head>
<body>
<button id="dd" onclick="clickHe()">我是计算机1班的</button>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
//注意:clickHe,不要写成click关键字,不然会有问题。
//格式与上面有些不同,不要写key了,传的data参数,可以是key=value形式也可以是json格式
<script>
function clickHe(){
$.post(
'ajax',
{username:"blues"},
function (aa, dd, hh) {
document.write(aa);
document.write(dd);
document.write(hh);
}
)
}
</script>
</head>
<body>
<button id="dd" onclick="clickHe()">我是计算机1班的</button>
</body>
</html>
$(选择器).serialize() 作用是把表单序列化为json字符串数据
$.ajax({
url: 'user?flag=login',
type: 'post',
data: {
username: username,
password: password
},
dataType : "json",
success: function (response) {
console.log(response);
if (response.code == 0) {
layer.msg(response.msg, {icon: 1, time: 1000}, function () {
window.location.href = 'index.jsp';
});
} else {
layer.alert(response.msg);
}
}