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

原生的ajax

发布时间:2020-12-16 00:48:27 所属栏目:百科 来源:网络整理
导读:testAjax.jsp : %@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%htmlheadmeta http-equiv="Content-Type" content="text/html; charset=UTF-8"titleInsert title here/titlescript type="text/javascript"function a

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();
	}

}

(编辑:李大同)

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

    推荐文章
      热点阅读