ajax(概述、jQuery封装的ajax)

一、概述

是一种无需加载整个网页就能更新部分网页的技术,如:注册的时候输入用户名后访问服务器,验证用户名是否已经存在

缺点:不能进行跨域访问(域名不同或者域名相同端口不同)

1、同步和异步

(1)同步:一步一步做,客户端向服务端发出请求,服务端在响应之前,客户端一直处于等待状态,也就是说客户端发起请求后在服务器响应之前不能再发起请求。

(2)异步:同时可以做多件事,客户端向服务端发出请求,不管服务端是否返回响应,客户端不必等待可以去做其他事情,也就是说可以在该请求的响应之前发起其他的请求。

2、Ajax的运行原理

(1)也就是说页面发起请求之后客户端可以进行其他操作,不用等待服务器,直到服务器返回数据给Ajax引擎后,会触发页面中的事件执行相应的功能。

(2)使用Ajax技术可以局部地刷新页面,从而减少请求和响应时间。

3、原生Ajax

(1)创建一个Servlet负责向客户端写入数据:

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");//设置服务器的编码,默认是ISO-8859-1
        response.setContentType("text/html; charset = utf-8");//告诉浏览器服务器的编码格式
        response.getWriter().write("武汉加油!!,中国加油!!!");
    }

(2)在jsp文件中获取服务器端的数据:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>原生Ajax</title>
    <script type="text/javascript">
      function print(){
        var xmlhttp;
        if(window.XMLDocument){
          xmlhttp=new XMLHttpRequest();
        }
        else{
          xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function(){
          if(xmlhttp.readyState==4&&xmlhttp.status==200){
            var response=xmlhttp.responseText;//接收文本格式的响应
            alert(response);
          }
        }
        xmlhttp.open("GET","/Ajax_war_exploded/ajaxservlet",true);//true为异步,请求目标的URL
        xmlhttp.send();//向服务器发送请求
      }
    </script>
  </head>
  <body>
      <button type="button" onclick="print()">点击获取服务器上的数据</button>
  </body>
</html>

XMLHttpRequest对象能够使用Http连接一个服务器,每次不必刷新页面,创建对象的时候根据浏览器的不同,创建方法存在差异:

火狐、谷歌等:

   xmlhttp=new XMLHttpRequest();

IE5、IE6浏览器:

 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

二、jQuery封装的AJAX

XMLHttpRequest在使用时比较繁琐,从创建到判定等操作需要较多的代码,因此,jQuery对XMLHttpRequest进行了很好的封装,提高了开发效率。

1、jQuery封装的AJAX的get方法(异步方式)

(1)创建jsp页面,向服务器提供数据

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>jQuery封装的Ajax</title>
    <script type="text/javascript" src="jq/jquery-1.8.3.js" ></script>
    <script type="text/javascript">
     function f(){
       $.get(
             "${pageContext.request.contextPath}/ajaxservlet",
               {"username":"Tom","age":13}
       );
     }
    </script>
  </head>
  <body>
      <button type="button" onclick="f()">请点击</button>
  </body>
</html>

因为该方法是封装在jQuery内部的,因此需要引入jq的相应文件。

传入服务器的参数以对象的形式传入

(2)创建一个servlet,获取jsp中的数据:

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      String username= request.getParameter("username");
      String age= request.getParameter("age");
       System.out.println(username);
       System.out.println(age);
    }

 (3)回调函数

jsp:

<script type="text/javascript">
     function f(){
       $.get(
             "${pageContext.request.contextPath}/ajaxservlet",
               {"username":"Tom","age":13},
               function (data) {
                 alert(data);
               },
               "text"
       );
     }
    </script>

servlet:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      String username= request.getParameter("username");
      String age= request.getParameter("age");
      response.getWriter().write("success");
       System.out.println(username);
       System.out.println(age);
    }

 

 其中jsp函数中的参数data为servlet返回的数据,第四个参数为数据的存储格式。

(4)servlet返回json类型的数据:

jsp:

 <script type="text/javascript">
     function f(){
       $.get(
             "${pageContext.request.contextPath}/ajaxservlet",
               {"username":"Tom","age":13},
               function (data) {
                 alert(data.age);
               },
               "json"
       );
     }

servlet:

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      String username= request.getParameter("username");
      String age= request.getParameter("age");
      response.getWriter().write("{"name":"tom","age":"11"}");
       System.out.println(username);
       System.out.println(age);
    }

 

 2、post方式

前端向服务器发送数据:不需要解决中文乱码问题,其它和get的一样。

服务器向客户端发送数据时:get和post方式都需要解决中文乱码码问题。

3、ajax方法

function f(){
       $.ajax(
               {
                 url:"${pageContext.request.contextPath}/ajaxservlet",
                 async:true,
                 type:"GET",
                 data:{"username":"Tom","age":13},
                 success:function (data) {
                   alert(data.age);
                 },
                 error:function () {
                   alert("服务器出错!!");
                 },
                 dataType:"json"
               }
       );

该方法可以说是涵盖了上述的get和post方法,而且与他们相比该方法更加灵活,只需要修改相应的参数即可对同步/异步,GET/POST提交方式等进行修改。

4、load方法

载入服务器的html文件并插入到DOM中。

原文地址:https://www.cnblogs.com/zhai1997/p/12246429.html