Ajax jquery 原理分析及其使用

引用:

关于异步与同步

异步传输是面向字符的传输,它的单位是字符;

同步传输是面向比特的传输,它的单位是桢,它传输的时候要求接受方和发送方的时钟是保持一致的。

XMLHttpRequest对象的属性。

     onreadystatechange  每次状态改变所触发事件的事件处理程序。

     responseText     从服务器进程返回数据的字符串形式。

     responseXML    从服务器进程返回的DOM兼容的文档数据对象。

     status           从服务器返回的数字代码,比如常见的404(未找到)和200(已就绪)

     statusText       伴随状态码的字符串信息

     readyState       对象状态值

     0 (未初始化) 对象已建立,但是尚未初始化(尚未调用open方法)

     1 (初始化) 对象已建立,尚未调用send方法

        2 (发送数据) send方法已调用,但是当前的状态及http头未知

     3 (数据传送中) 已接收部分数据,因为响应及http头不全,这时通过responseBody和responseText获取部分数据会出现错误,

     4 (完成) 数据接收完毕,此时可以通过通过responseXml和responseText获取完整的回应数据

Method :Post  发送数据方式 url send(特属于post方式)

        Get 发送数据方式  url

 

 

原生Ajax

index.jsp
<%@ page language="java" contentType="text/html;charset=UTF-8"  pageEncoding="UTF-8"%>
<!DOCTYPEhtml PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html; charset=UTF-8">
<title>Insert title here</title>
<scripttype="text/javascript">
    window.οnlοad=function(){
        var button = document.getElementById("button");
        var name = document.getElementById("name");
        var password = document.getElementById("password");  
        button.οnclick=function(){
            var xhr =new XMLHttpRequest();
            //xhr.open("get","AjaxServlet",true);
            //xhr.open("get","AjaxServlet?name="+name.value+"&password="+password.value,true);
            xhr.open("post","AjaxServlet",true);
            xhr.onreadystatechange= function(){
                if( xhr.status == 200 && xhr.readyState== 4 ){
                    console.log(xhr.responseText );
                }
            };  
            xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
            xhr.send("name="+name.value+"&password="+password.value);
            //xhr.send(null);
        };
    };
</script>
</head>
<body>
<label>登录</label><br/>
<label>帐号</label>
<inputtype="text"name="name"id="name"/><br/>
<label>密码</label>
<inputtype="password"name="password"id="password"/><br/>
<inputtype="submit"id="button"/>
</body>
</html>
 
 
 
AjaxServlet.java
package com.rl.ajax.serlvet;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AjaxServlet extendsHttpServlet {
       privatestatic final long serialVersionUID = 1L;
       publicAjaxServlet() {
              super();
       }
       protectedvoid doGet(HttpServletRequest request,
                     HttpServletResponseresponse) throws ServletException, IOException {         
              @SuppressWarnings("unchecked")
              Map<String,String[]>maps = request.getParameterMap();
              for(Entry<String,String[]> es : maps.entrySet()){
                     response.getWriter().write(es.getKey()+":"+es.getValue()[0]+"\n");
              }   
       }
       protectedvoid doPost(HttpServletRequest request,
                     HttpServletResponseresponse) throws ServletException, IOException {
              doGet(request,response);
       }
}


 

 

 

Jquery Ajax

jqueryIndex.jsp
<%@ page language="java"contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPEhtml PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<%
   String path = request.getContextPath();
   String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
   pageContext.setAttribute("path", basePath);
%>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html; charset=UTF-8">
<title>Insert title here</title>
<scripttype="text/javascript"src="${pageScope.path }jquery/jquery-1.11.0.min.js"></script>
<scripttype="text/javascript"src="${pageScope.path }Js/jqueryIndex.js"></script>
</head>
<body>
<label>登录</label><br/>
<label>帐号</label>
<inputtype="text"name="name"id="name"/><br/>
<label>密码</label>
<inputtype="password"name="password"id="password"/><br/>
<inputtype="submit"id="button"/>
</body>
</html>
jqueryIndex.js
$(function(){
    $("#button").click(function(){
//      console.log("按钮触发");
//      $.ajax({
//          type:"get",
//          url:"AjaxServlet",
//          data:{
//              "name":$("#name").val(),
//              "password":$("#password").val()
//          },
//          success:function( message,textStatus){
//              console.log(message,textStatus);
//          },
//          err:function(XMLHttpRequest,textStatus, errorThrown){
//              console.log(XMLHttpRequest,textStatus, errorThrown);
//          }
//      });   
//      $.get("AjaxServlet",{"name":$("#name").val(),"password":$("#password").val()},function(message,textStatus){
//          console.log(message,textStatus);
//      });
//      $.ajaxSetup({
//          err:function(XMLHttpRequest,textStatus, errorThrown){
//              console.log(XMLHttpRequest,textStatus, errorThrown);
//          }
//      });
        $.post("AjaxServlet",{"name":$("#name").val(),"password":$("#password").val()},function(message,textStatus){
            console.log(message,textStatus);
            });
    });
});AjaxServlet.java
package com.rl.ajax.serlvet;
 
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
 
public class AjaxServlet extendsHttpServlet {
       privatestatic final long serialVersionUID = 1L;
 
       publicAjaxServlet() {
              super();
       }
 
       protectedvoid doGet(HttpServletRequest request,
                     HttpServletResponseresponse) throws ServletException, IOException {
             
              @SuppressWarnings("unchecked")
              Map<String,String[]>maps = request.getParameterMap();
              for(Entry<String,String[]> es : maps.entrySet()){
                     response.getWriter().write(es.getKey()+":"+es.getValue()[0]+"\n");
              }
             
       }
 
       protectedvoid doPost(HttpServletRequest request,
                     HttpServletResponseresponse) throws ServletException, IOException {
              doGet(request,response);
       }
 
}


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值