Ajax使用

什么是Ajax?

Ajax是一种创建快速动态网页的技术,通过与后台服务器进行少量数据交互,可以使网页异步更新,这意味着可以在不加载整个页面的情况下,局部更新页面某个部分。

原生Ajax的使用:

XMLHttpRequest是Ajax使用的基础,

  1.创建XMLHttpRequest对象:
    var xmlhttp;
       <!--创建xmlhttprequest对象-->
       if(window.XMLHttpRequest){
           //IE7,chrome,firefox等
           xmlhttp = new XMLHttpRequest();
       }else{
           //IE5,IE6
           xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
       }

 定义变量xmlhttp,判断浏览器是否内置XMLHttpRequest,现代浏览器基本都内建XMLHttpRequest对象,IE5,IE6使用ActiveObject对象

  2.使用XMLHttpRequest对象发送请求:
   get方式 :
     xmlhttp.open("get","/TestServlet?name='zhangsan'&pass='123'",true);
        xmlhttp.send();
    Post方式:
     xmlhttp.open("post","/TestServlet",true);
        //使用post方式带数据,要添加头,说明提交的数据时一个经过Url编码的form表单数据
        xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xmlhttp.send("name=lisi&pass=456");

    open方法中参数:1、get:表示发送get请求,如果是post则发送post请求;

            2、/TestServlet?name='zhangsan'&pass='123':表示发送请求的URL,以及传递的参数;post方式传递的参数不能加在URL后面,post方式的参数在send方法中传递

            3、true:表示发送异步请求,false:表示不发送异步请求

   使用send方法发送;

  3.使用onreadystatechange事件判断响应状态,readyState状态每改变一次就会触发一次onreadystatechange

  xmlhttp.readyState有五种状态:0 :表示请求未初始化

                1:表示服务器连接已建立

                2:表示请求已接收

                3:表示请求处理中

                4:表示请求已完成,且响应已就绪

  xmlhttp.status的状态:200:表示“OK”
              404:表示未找到
  判断如果readyState状态是4,且status状态是200,则接收到了服务器响应的数据
 
  
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status == 200){
alert(xmlhttp.responseText)
}
}
   4.获取响应数据,有两种方式:1.响应数据格式为字符串,使用responseText接收,2.响应数据为xml形式,使用responseXML来接收,如上述代码xmlhttp.responseText

  完整代码如下:

  1.Servlet代码:

    
package com.ypf.servlet;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/TestServlet")
public class TestServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        String pwd = req.getParameter("pass");
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().write("收到了请求,信息为"+name+"--->"+pwd);
    }
}
TestServlet

   2.jsp页面代码

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2019/6/1 0001
  Time: 13:06
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Ajax测试</title>
<script>
    function SendGet() {
       var xmlhttp;
       <!--创建xmlhttprequest对象-->
       if(window.XMLHttpRequest){
           //IE7,chrome,firefox等
           xmlhttp = new XMLHttpRequest();
       }else{
           //IE5,IE6
           xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
       }
       xmlhttp.open("get","/TestServlet?name=zhangsan&pass=123",true);
       xmlhttp.send();
       xmlhttp.onreadystatechange=function(){
            if(xmlhttp.readyState==4 && xmlhttp.status == 200){
                alert(xmlhttp.responseText)
            }
        }
    }
    function SendPost() {
        var xmlhttp;
        <!--创建xmlhttprequest对象-->
        if(window.XMLHttpRequest){
            //IE7,chrome,firefox等
            xmlhttp = new XMLHttpRequest();
        }else{
            //IE5,IE6
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.open("post","/TestServlet",true);
        //使用post方式带数据,要添加头,说明提交的数据时一个经过Url编码的form表单数据
        xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xmlhttp.send("name=lisi&pass=456");
        xmlhttp.onreadystatechange=function(){
            if(xmlhttp.readyState==4 && xmlhttp.status == 200){
                alert(xmlhttp.responseText)
            }
        }
    }
</script>
</head>
<body>
<h2>Ajax发送get请求</h2>
<button onclick="SendGet()">Ajax发送get请求</button>
<hr>
<h2>Ajax发送post请求</h2>
<button onclick="SendPost()">Ajax发送post请求</button>

</body>
</html>
JSP页面

JQuery封装之后Ajax使用

 1.引入Jquery库,下载或者在网页加载;网页加载方式

<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js"></script>

 2.JQuery中使用$.ajax方式:

$.ajax({
          url:"/TestServlet",
          type:"get",
          data:"name=王五&pass=789",
          success:function (result) {
               alert(result);
          }
      });

 

url:请求路径,type:发送请求类型,data:发送的数据(get方式可加在url之后),succse:请求成功调用的回调函数,这种方式参数有20多种,以上是基本的参数,

其他参数可参考:https://www.cnblogs.com/tylerdonet/p/3520862.html

简单的get方式也可以替换为:$.get();这种get方式只有四个参数:1.url:请求路径,2.data:发送请求数据,3.请求成功的回调函数,4.响应的数据类型(text,json,xml等)

    $.get(
                "/TestServlet",
                "name=赵云&pass=258",
                function(result,status,xhr){
                    alert(result);
                    alert(status);
                },
          "text" );

 post方式使用:$.post(),与$.get()参数类型一致,四个参数;

Servlet代码与原生Ajax方式一致;

Jsp完整代码如下:

    
<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2019/6/1 0001
  Time: 13:06
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Ajax测试</title>
    <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js"></script>
<script>
    
    $(document).ready(function () {
        $(".Jajaxget").click(function () {
            /*$.ajax({
                url:"/TestServlet",
                type:"get",
                data:"name=王五&pass=789",
                success:function (result) {
                    alert(result);
                }
            });*/
            //规定有四个参数,1.url,2.data发送的数据,3.请求成功时运行的函数,4.返回值类型
            $.get(
                "/TestServlet",
                "name=赵云&pass=258",
                function(result,status,xhr){
                    alert(result);
                    alert(status);
                },"text"
            );
        });
        $(".Jajaxpost").click(function () {
            /*$.ajax({
                url:"/TestServlet",
                type:"post",
                data:"name=赵六&pass=147",
                success:function (result) {
                    alert(result);
                }
            });*/
            $.post(
                "/TestServlet",
                "name=诸葛亮&pass=369",
                function(result,status,xhr){
                    alert(result);
                    alert(status);
                },"text"
            );
        });
    });
</script>
</head>
<body>
<h2>Jquery封装Ajax发送get请求</h2>
<button class="Jajaxget">Jquery封装Ajax发送get请求</button>
<h2>Jquery封装Ajax发送post请求</h2>
<button class="Jajaxpost">Jquery封装Ajax发送post请求</button>
</body>
</html>
JSP页面

 

转载于:https://www.cnblogs.com/YpfBolg/p/10959922.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值