原始ajax的基本实现步骤

一:传统的web项目中,用户的每次页面操作都会产生一个Http请求发送给服务器,服务器接收到请求处理完数据后会返还一个界面给前段,这样用户的每次操作都将会得到一个新的界面。

二:ajax由多种技术合成的一个访问服务器的技术。可实现异步访问局部刷新界面,其核心技术是XmlHttpRequest

三:基本实现步骤

3. 1.创建ajax引擎

   3. 1.1 IE浏览器

       if(window.XMlHttpRequest){

                   xhr = new XMLHttpRequeest();

         }

   3.1.2 非IE浏览器

      if(window.ActiveXObject){

            xhr = new ActiveXObject(Microsoft.XMLHTTP);

     }

3.2 指定回调函数(复写onreasystatechange()方法)

   xhr.onreadystatechange=function(){

       ....

   }

3.3 创建请求

    xhr.open("请求方式","url","是否异步");

    说明:请求方式为get请求是,参数在url后面直接追加,若为post请求则在send()方法中传参格式为“name=”+name+"pswd="+pswd,且用post请求是必须设置请求头信息

    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')

3.4 发送请求

   xhr.send();

四:代码整体参考

 4.1前端

<script type="text/javascript">
	function submit(){
		var name=document.getElementById("username").value;
		var xhr;
			//创建ajax引擎
			if(window.XMLHttpRequest){
				xhr = new XMLHttpRequest();
			}else if(window.AtiveXObject){
				xhr = new ActiveXObject("Microsoft.XMLHTTP");
			}
			//指定回调函数(复写onreadystatuschange方法)
			xhr.onreadystatechange=function(){
				if(xhr.readyState==4){
					if(xhr.status==200){
						var result = xhr.responseText;
							alert(result);
						}
				}
			};
			//创建请求
			xhr.open("post", "${pageContext.request.contextPath}/loginServlet",true);
			xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
			//发送请求
			xhr.send("name="+name);
	}
</script>
<body>
		用户名:<input type="text" name="username" id="username" />
		<input type="button" name="tijiao" value="提交" οnclick="submit()"/>
  </body>

4.2 后台


@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("type=text/html,cahrset=utf-8");
		resp.setCharacterEncoding("utf-8");
		String name = (String)req.getParameter("name");
		System.out.println("name---"+name);
		resp.getWriter().write(name);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("type=text/html,charset=utf-8");
		String name=req.getParameter("name");
		System.out.println(name);
	
		resp.getWriter().write(name);
	}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值