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

AJAX体验--Post请求

发布时间:2020-12-16 01:52:00 所属栏目:百科 来源:网络整理
导读:和get不一样的地方: * open:xmlHttp.open(" POST " ....); * 添加一步: 设置Content-Type请求头 : xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); * send:xmlHttp.send("username=zhangSanpassword=123");// 发送请求

和get不一样的地方:

* open:xmlHttp.open("POST" ....);

* 添加一步: 设置Content-Type请求头
> xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

* send:xmlHttp.send("username=zhangSan&password=123");//发送请求时指定请求体

jsp页面:

<body>
<div>
<input type="button" id="btn" value="点击一下"/><br/>
<span id="inner"></span>
</div>
</body>

js代码:

<script>
function createXmlHttpRequest(){
var xmlHttpRequest ;//声明一个xmlHttpRequest对象
try{
//大多数浏览器都支持的创建xmlHttpRequest 对象的方式
xmlHttpRequest = new XMLHttpRequest();
}catch(e){
try{
//==>> IE6.0版本下的创建XMLHttpRequest的方式
xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
//==>> IE5.0及以下创建XMLHttpRequest 对象的方式
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
throw e;
}
}
}
return xmlHttpRequest;
}
window.onload = function(){//文档一开始就执行


var btn = document.getElementById("btn");//得到btn对象
btn.onclick = function(){//在btn上绑定click对象,注意这里的onclick都是小写,我当时写的时候把c字母写成大写了
var xmlHttp = createXmlHttpRequest();//得到xmlHttpRequest 对象

/**
注意这里改变了
*/
xmlHttp.open("POST","AjaxDemo",true);//get方式请求open("请求的方式","请求的uri","是否设置成异步的方式")
//添加
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

//这里也改变了
xmlHttp.send("username=张三&password=123");
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
var text = xmlHttp.responseText;//得到从服务器传送回来的数据
var inner = document.getElementById("inner").innerHTML = text;//写入到span中

}
};
};

};
</script>


servlet中得dopost请求:

/**
* 接受post 请求
*/
protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
// TODO Auto-generated method stub
// 意思是告诉浏览器我的这个内容是文本html,然后字符编码是utf-8,如果你不告诉浏览器编码,那么浏览器,一般会根据系统默认编码来解析你的页面中的字符。
response.setContentType("text/html;charset=utf-8");
//向服务器发送请求时设置编码方式为utf-8;
request.setCharacterEncoding("UTF-8");
String username = request.getParameter("username");//得到jsp页面传送的数据 张三
String password = request.getParameter("password");//123

//在控制台打印出来,测试用的
System.out.println(username);
System.out.println(password);

response.getWriter().println("Hello AJAX!!!"+username);//通过response对象将"Hello AJAX!!! 写回到jsp页面" response.getWriter().flush();//刷新一下 response.getWriter().close();//关闭writer对象 }

(编辑:李大同)

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

    推荐文章
      热点阅读