原生的ajax

前端之家收集整理的这篇文章主要介绍了原生的ajax前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

testAjax.jsp :

<%@ page language="java" 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 type="text/javascript">
function ajax(){
	var xhr=getXhr();
	xhr.onreadystatechange=function(){
		if(xhr.readyState==4){
			if(xhr.status==200){
				document.getElementById("resText").innerHTML=xhr.responseText;
			}
		}
	}
	xhr.open('get','test',true);
	xhr.send(null);
}

function getXhr(){
	var xhr=null;
	if(window.ActiveXObject){
		xhr=new ActiveXObject("Microsoft.XMLHTTP");
	}else if(window.XMLHttpRequest){
		xhr=new XMLHttpRequest();
	}
	return xhr;
}
</script>
</head>
<body>

<input type="button" value="以ajax方式获取数据" onclick="ajax();">
<div id="resText"></div>

</body>
</html>
TestServlet.java :
public class TestServlet extends HttpServlet {

	public void doGet(HttpServletRequest request,HttpServletResponse response) 
		throws ServletException,IOException {
		PrintWriter pw=response.getWriter();
		pw.print("hello ajax...");
		pw.close();
	}

}
为Servlet映射的url为test。

点击按钮后:

如果get方式要传递参数,可以这样:

xhr.open('get','test?name=tom&age=23',true);
public class TestServlet extends HttpServlet {

	public void doGet(HttpServletRequest request,IOException {
		String name=request.getParameter("name");
		String age=request.getParameter("age");
		PrintWriter pw=response.getWriter();
		pw.print("name:"+name+",age:"+age);
		pw.close();
	}

}
原文链接:https://www.f2er.com/ajax/165574.html

猜你在找的Ajax相关文章