Ajax(2):post请求

本文介绍如何通过XMLHttpRequest发送POST请求进行用户名验证。详细展示了register.jsp页面中JavaScript代码的具体实现过程,包括创建XMLHttpRequest对象、设置请求状态变化监听器、配置请求头并发送带参数的POST请求。

本篇文章与上篇文章大体类似,不同的只不过是利用XMLHttpRequest异步地向服务器发送post请求。

除了register.jsp文件,其余三个文件全部保持不变。

register.jsp :

<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script>
function getXmlHttpRequest(){
var xhr=null;
if((typeof XMLHttpRequest)!='undefined'){
xhr=new XMLHttpRequest();
}else{
xhr=new ActiveXObject("Microsoft.XMLHttp");
}
return xhr;
}

function valiUsername(){
var xhr=getXmlHttpRequest();
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200){
var doc=xhr.responseText;
document.getElementById('username_msg').innerHTML=doc;
}else{
document.getElementById('username_msg').innerHTML='sorry,system error...';
}
}else{
document.getElementById('username_msg').innerHTML='checking...';
}
}
var url="valiusername.do";
xhr.open("post",url,true);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send("username="+document.getElementById('n1').value);
}
</script>
</head>
<body>
<form action="register.do" method="post">
username:<input type="text" name="username" id="n1" onblur="valiUsername();">
<span style="color:red" id="username_msg"></span><br>
password:<input type="password" name="password"><br>
<input type="submit" value="register">
</form>
</body>
</html>
与上篇文章的get请求相比,post请求有3点不同:

① xhr.open("post",url,true);这里将get 改为了post。

② xhr.send("username="+document.getElementById('n1').value);这里参数不再为null,对于post请求,要传递的参数放在send方法里。

③ 最重要的一点,必须在open和send方法之间加上代码:xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值