js_ajax_简单实现ajax

@WebServlet("/ajax.do")
public class HelloAjax extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public HelloAjax() {
        super();
        // TODO Auto-generated constructor stub
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	response.getWriter().write("Ajax Test");
	}

}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
window.onload=init;
function init(){
	var btn=document.getElementById("btn");
	btn.onclick=getdata;
}
function getdata(){
	var xhr;
	if (window.XMLHttpRequest) 
	  {// code for IE7+, Firefox, Chrome, Opera, Safari 
		xhr=new XMLHttpRequest(); 
	  } 
	else 
	  {// code for IE6, IE5 
		xhr=new ActiveXObject("Microsoft.XMLHTTP"); 
	  }
	xhr.onreadystatechange=function(){
		if(xtr.readyState==4&&xtr.status==200){
			document.getElementById("display").innerHTML=xhr.responseText;
		}
	}
	xhr.open("get","ajax.do",true);
	xhr.send();
	
	
}
</script>
</head>
<body>
<input type="button" id="btn" value="测试">
<div id="display"></div>
</body>
</html>

注意:(1).ajax可以实现不加载整个页面的情况下,对页面某部分进行更新

如何使用ajax:

1.创建XMLHttpRequest对象

2.检测XMLHttpRequest状态,在合适的时候进行处理

3.发送请求

猜你喜欢

转载自blog.csdn.net/HZPHYT/article/details/81168027
今日推荐