ajax入门:与servlet交互发送post请求实例
发送post请求(如果发送请求时需要带参数,一般都用post请求)
*open:xmlHttp.open("open"........);
*添加一步:设置Content-Type请求头:
--xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
*send:xmlHttp.send("username=zhangsan&password=123"); //发送请求时指定请求体
AServlet.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("hello AJAX");
response.getWriter().print("hello ajax!!!!");
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username =request.getParameter("username"); ///获取用户名
System.out.println("(post)hello AJAX"+username);
response.getWriter().print(" (post)hello ajax!!!!"+username);
}
}
ajax-post.jsp
<%@ page language="java" contentType="text/html; utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
<script type="text/javascript">
//创建异步对象
function createXMLHttpRequest(){
try{
return new XMLHttpRequest();
}catch(e){
try{
return new ActiveXObject("Msxm12.XMLHTTP");
}catch(e){
try{
return new AtiveXObject("Microsoft.XMLHTTP");
}catch(e){
alert("用的啥浏览器啊?");
throw e;
}
}
}
}
window.onload = function(){ //文档加载完毕后执行
var btn = document.getElementById("btn");
btn.onclick = function(){ //给按钮的点击事件注册监听
//ajax的四步操作,得到服务器的响应
//把响应结果显示到h1元素中
// 1. 得到异步对象
var xmlHttp = createXMLHttpRequest();
//2.打开与服务器的链接
// get 指定请求方式 指定请求url 指定是否为异步请求
/**************修改open方法,指定请求方式为post********************/
xmlHttp.open("POST","<c:url value='/AServlet'/>",true);
/******************设置请求头***************************/
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//3.发送请求
/***************发送时,指定请求体*******************/
xmlHttp.send("username=zhangsan&password=123");// get请求没有请求体,但而要给出null 如果不给(null)可能会造成部分浏览器无法发送
// 4.给异步对象的 onreadystatechange 事件注册监听器
xmlHttp.onreadystatechange = function(){ //当xmlHttp的状态发生变化时执行
//双重判断:xmlHttp的状态为4 (服务器响应结束),以及服务器响应状态码为200(响应成功)
if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
//获取服务器响应结果
var text = xmlHttp.responseText;
//获取h1元素
var h1 = document.getElementById("h1");
h1.innerHTML = text;
}
};
};
};
</script>
</head>
<body>
<button id="btn">点击这里</button>
<h1 id="h1"></h1>
</body>
</html>
阅读剩余
版权声明:
作者:Tin
链接:http://www.tinstu.com/733.html
文章版权归作者所有,未经允许请勿转载。
THE END