加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ajax(2):post请求

发布时间:2020-12-16 01:01:06 所属栏目:百科 来源:网络整理
导读:本篇文章与上篇文章大体类似,不同的只不过是利用XMLHttpRequest异步地向服务器发送post请求。 除了register.jsp文件,其余三个文件全部保持不变。 register.jsp : %@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%htmlheadmeta http-e

本篇文章与上篇文章大体类似,不同的只不过是利用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",true);这里将get 改为了post。

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读