异步处理ajax和前后端数据交互json

简介: 异步处理ajax和前后端数据交互json

ajax和json



Ajax

同步和异步:
  a标签是同步,调用完形成新的页面,页面会刷新.原页面在a标签后面的代码将不执行处于等待状态.    而异步请求不会.异步此页面的其他代码会继续执行
应用场景:
  用户名是否存在的校验,百度自动补全功能,商品查找,搜索图片
注意:
  ajax不能跨函数,不能跨页面

异步:强大之处服务器处理不影响浏览器的其他操作,增强用户体验度

原生ajax

入门案例:
  1:创建一个核心对象(XMLHttPRequest)
      该对象称之为ajax引擎
    2:编写onreadystatechange事件所调用的函数
      回到函数
    3:确定请求方式和请求路径
  4:发送请求
    5:处理返回结果

原生ajax案例:

index.jsp
<%--
  Created by IntelliJ IDEA.
  User: hp
  Date: 2020/5/14
  Time: 13:27
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
<h3>原生ajax</h3>
  <a href="js_01.jsp">原生ajax入门</a>
  </body>
</html>
js_01.jsp
<%--
  Created by IntelliJ IDEA.
  User: hp
  Date: 2020/5/14
  Time: 13:29
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script type="text/javascript" src="/day07/js/jquery-3.3.1.js"></script>
    <script>
        function sendAjax() {
            //发送sjax请求
            //1:创建ajax核心对象(xmlhttprequest)ajax引擎
            var xmlhttp;
            if(window.XMLHttpRequest){
                xmlhttp=new XMLHttpRequest();
            }else{
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            //2:编写onreaystatechange事件所调用的函数
            xmlhttp.onreadystatechange=function () {
                //1:监听ajax引擎的状态
                //5:处理结果
                if(xmlhttp.readyState==4 && xmlhttp.status==200){
                    $("#spId").html(xmlhttp.responseText);
                }
            }
            //3:编写ajax请求的方式和地址
            xmlhttp.open("post","demo1");
            //4:发送请求
            xmlhttp.send();
        }
    </script>
</head>
<body>
<input type="button" value="发送ajax请求" onclick="sendAjax()"/><br>
<span id="spId"></span>
</body>
</html>
Demo1Servlet.java
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(name = "Demo1Servlet", urlPatterns = "/demo1")
public class Demo1Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("demo1servlet执行了");
        response.getWriter().print("hello ajax 你好");
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
原生ajax的属性
onreadystatechange事件
  在ajax对象状态发生改变时,就会出发该时间
  对象.onreadystatechange=function(){}
redaystate
  存在XMLHTTPRequest的状态
    0:请求未初始化(见不到的就相当于还没创建对象)
    1:服务器连接已建立
    2:请求已接收
    3:请求处理中
    4:请求已完后,且响应已就绪
status
  响应状态码:
    if(xmlhttp.readystate==4&&xmlhttp.status==200){
        //执行的代码片段
    }
responseText
  获取服务器响应回来的文本信息
原生ajax的方法
open(method,url,[async]);
  设置请求的类型,请求地址以及是否异步处理请求
  method:请求的类型;get或post
  url:文件在服务器上的位置
  async:true(异步)或false(同步)
send([string]);
  将请求发送到服务器
    string:存放post请求携带的参数
在post请求时要设置请求参数的mime类型
  xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");


jQuery中的Ajax


$.post(url,[params],fn,[type])

发送post请求


url:请求的路径


params:请求的参数


格式1:字符串key1=value1&key2=value2


格式2:json格式:


{“key1”:“value1”,“key2”:“value2”}


fn:回调函数


function(data){


//data:响应回来的数据(xmlHttp.responseText)


}


type:返回内容的格式 text xml json


默认返回的是text类型的数据,一般不需要自己设置,设置的话一般设置为json


ajax的post请求案例:

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
<h3>原生ajax</h3>
  <a href="js_01.jsp">原生ajax入门</a>
<h3>jQuery的ajax</h3>
<a href="js_02.jsp">jQuery的ajax</a>
  </body>
</html>

js_02.jsp

<%--
  Created by IntelliJ IDEA.
  User: hp
  Date: 2020/5/14
  Time: 13:29
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script type="text/javascript" src="js/jquery-3.3.1.js"></script>
    <script>
        function sendAjax() {
            var url = "demo2";
            var params ={"username":"汤姆","password":"123"};
            function fun(data) {
                alert(data);
            }
            $ .post(url, params, fun,"text");
        }
    </script>
</head>
<body>
<input type="button" value="发送ajax请求" onclick="sendAjax()"/><br>
<span id="spId"></span>
</body>
</html>

Demo02Servlet.java

@WebServlet(name = "Demo3Servlet", urlPatterns = "/demo2")
public class Demo3Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //解决乱码
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().print(request.getParameter("username")+":"+request.getParameter("password"));
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
如果换为get请求则 $.get(url,[params],fn,[type])即可
$.ajax写法想发post或者get都可以
$.ajax({url,[settings]})
  url:请求路径
  type:请求方式
  data:请求参数
  success:请求成功后的回调函数
  error:请求失败后调用的函数
  dateType:服务器返回的数据类型
    一般不需要自己设置,要设置的话一般设置为json
  async:设置是否为异步提交,默认为true(异步提交)
eg:
$.ajax({
  url:url,
  data:params,
  type:"post",
  success:f,
  error:ef,
  async:true
})

json

概述:
  JavaScript对象表示法,是存储和交换文本信息的语法,类似xml,  比xml更小,更快,更衣解析.
格式:
  格式1:json对象
    {"key":"value","key2":"value2"}//key为String类      型,value任意类型
  格式2:json数组
    ["aa","bb"]
  格式3:混合json
    [{"name":"张三","age":"11"},{"name":"张三2","age":"21"}]
    {"student":["张三","李四"]}
获取json对象格式的值直接:对象.key

java对象转换为json数据

常见的工具类:
  jsonlib
  fastjson(阿里巴巴的)
  gson(谷歌的)
    Jackjson(为springmvc默认的转换方式)

案例一:检测用户名是否被注册

需求分析:
  再注册页面上,当用户在用户名的输入框输入完成后,也就是失去焦点事件发送ajax请求,检验用户名是否存在
  该用户名已存在:
    提示:"该用户名已被占用"
    该用户名不存在:
    提示:"√"
技术分析:
  blur:失去焦点事件
  ajax:
  $.ajax({
      url:"",
        data:"",
        type:"",
        success:f,
        error:f,
        dataType:"text",
        async:true
  })
步骤分析:
  前台:
    提供注册页面,给用户名的输入框添加失去焦点事件
        输入框对象.blur(function(){
          //发送ajax请求
        })

demo1.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script type="text/javascript" src="js/jquery-3.3.1.js"></script>
    <script>
        //页面加载成功事件
        $(function () {
            //用户名输入框的失去焦点事件
            $("input[name='username']").on("blur",function () {
                //获取用户输入的name值
               var username=$(this).val();
               //使用ajax异步处理
                $.ajax({
                    url:"user",
                    data:{"username":username},
                    type:"post",
                    success:function (data) {
                        $("#nameMsg").html(data);
                    },
                    dataType:"text",
                    async:true
                })
            })
        })
    </script>
</head>
<body>
<form action="">
    <table align="center" border="1px solid red" width="300px" height="100px">
        <tr>
            <th colspan="2" align="center">
                用户表单
            </th>
        </tr>
        <tr>
            <td>用户名:</td>
            <td>
                <input type="text" name="username">
                <span id="nameMsg"></span>
            </td>
        </tr>
        <tr>
            <td>密码:</td>
            <td>
                <input type="password" name="pwd">
            </td>
        </tr>
        <tr>
            <td colspan="2" align="center">
                <input type="submit" id="subId" value="提交"/>
            </td>
        </tr>
    </table>
    <br>
</form>
</body>
</html>

UserServlet.java

@WebServlet(name = "UserServlet", urlPatterns = "/user")
public class UserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //获取前端传来的userName
        String username = request.getParameter("username");
        //调用service查看此用户名是否存在
        UserService userService = new UserService();
        User exist = userService.exist(username);
        if (exist==null) {
            response.getWriter().print("√");
        }else{
            response.getWriter().print("用户名已存在");
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

UserService.java

public class UserService {
    public User exist(String username){
        UserDao userDao = new UserDao();
         return  userDao.exist(username);
    }
}

UserDao.java

public class UserDao {
    public User exist(String username){
        try {
            String sql = "select * from user where name = ? ";
            JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
            return template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), username);
        } catch (DataAccessException e) {
            return null;
        }
    }
}
案例二:异步自动填充

demo2.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
  .content{
    width:643px;
    margin:200px auto;
    text-align: center;
  }
  input[type='text']{
    width:530px;
    height:40px;
    font-size: 14px;
  }
  input[type='button']{
    width:100px;
    height:46px;
    background: #38f;
    border: 0;
    color: #fff;
    font-size: 15px
  }
  .show{
    width: 535px;
    border: 1px solid #999;
    border-top: 0;
        display: none;
  }
</style>
<script type="text/javascript" src="js/jquery-3.3.1.js"></script>
<script type="text/javascript">
  //搜索框联想词的单击事件
  function fn(ele) {
        $("input[name='word']").val($(ele).html());
    }
  $(function () {
        $("input[name='word']").on("keyup",function () {
            $.ajax({
        url:"demo2",
        data:{"username":$(this).val()},
        type:"post",
        success:function (data) {
          if(data!="null"&&data.length>0){
              var str="";
                        $("div>div").empty();
              $.each(data,function (index,ele) {
                            str += "<span οnclick='fn(this)'>"+ele+"</span><br>";
                        });
                        $("div>div").html(str);
                        $("div>div").show();
          }else{
                        $("div>div").hide();
          }
                },
        dataType:"json",
        async:true
      })
        })
    })
</script>
</head>
<body>
  <div class="content">
    <img alt="" src="img/logo.png"><br/><br/>
    <input type="text" name="word">
    <input type="button" value="搜索一下">
    <div class="show"></div>
  </div>
</body>
</html>

Demo2Servlet.java

@WebServlet(name = "Demo2Servlet", urlPatterns = "/demo2")
public class Demo2Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        List<String> userList = new UserService().likeName(request.getParameter("username"));
        //将list转换为json
        String listJson = new ObjectMapper().writeValueAsString(userList);
        System.out.println("listJson======="+listJson);
        response.getWriter().print(listJson);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

service.java

public class UserService {
    public User exist(String username){
        UserDao userDao = new UserDao();
         return  userDao.exist(username);
    }
    public List<String> likeName(String username){
        UserDao userDao = new UserDao();
        return  userDao.likeName(username);
    }
}

dao.java

public class UserDao {
    public User exist(String username){
        try {
            String sql = "select * from user where name = ? ";
            JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
            return template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), username);
        } catch (DataAccessException e) {
            return null;
        }
    }
        public List<String> likeName(String username){
        try {
            String sql = "select name from user where name like ?  ";
            JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
            return template.queryForList(sql, String.class, username+"%");
        } catch (DataAccessException e) {
            return null;
        }
    }
}


目录
相关文章
|
21天前
|
存储 JSON API
淘系API接口(解析返回的json数据)商品详情数据解析助力开发者
——在成长的路上,我们都是同行者。这篇关于商品详情API接口的文章,希望能帮助到您。期待与您继续分享更多API接口的知识,请记得关注Anzexi58哦! 淘宝API接口(如淘宝开放平台提供的API)允许开发者获取淘宝商品的各种信息,包括商品详情。然而,需要注意的是,直接访问淘宝的商品数据API通常需要商家身份或开发者权限,并且需要遵循淘宝的API使用协议。
淘系API接口(解析返回的json数据)商品详情数据解析助力开发者
|
9天前
|
JSON JavaScript 前端开发
Haskell中的数据交换:通过http-conduit发送JSON请求
Haskell中的数据交换:通过http-conduit发送JSON请求
|
7天前
|
JSON 前端开发 JavaScript
JavaWeb基础8——Filter,Listener,Ajax,Axios,JSON
Filter过滤器、Listener监听器、AJAX、 同步、异步优点和使用场景、Axios异步框架、JSON、js和JSON转换、案例,Axios + JSON 品牌列表查询和添加
JavaWeb基础8——Filter,Listener,Ajax,Axios,JSON
|
12天前
|
存储 JSON API
Python编程:解析HTTP请求返回的JSON数据
使用Python处理HTTP请求和解析JSON数据既直接又高效。`requests`库的简洁性和强大功能使得发送请求、接收和解析响应变得异常简单。以上步骤和示例提供了一个基础的框架,可以根据你的具体需求进行调整和扩展。通过合适的异常处理,你的代码将更加健壮和可靠,为用户提供更加流畅的体验。
36 0
|
22天前
|
JSON Java API
Jackson:SpringBoot中的JSON王者,优雅掌控数据之道
【8月更文挑战第29天】在Java的广阔生态中,SpringBoot以其“约定优于配置”的理念,极大地简化了企业级应用的开发流程。而在SpringBoot处理HTTP请求与响应的过程中,JSON数据的序列化和反序列化是不可或缺的一环。在众多JSON处理库中,Jackson凭借其高效、灵活和强大的特性,成为了SpringBoot中处理JSON数据的首选。今天,就让我们一起深入探讨Jackson如何在SpringBoot中优雅地控制JSON数据。
30 0
|
23天前
|
JSON 数据处理 数据格式
Python中JSON结构数据的高效增删改操作
Python中JSON结构数据的高效增删改操作
|
23天前
|
XML JSON 定位技术
在Python中操纵json数据的最佳方式
在Python中操纵json数据的最佳方式
|
1月前
|
JSON 前端开发 JavaScript
|
26天前
|
存储 SQL JSON
【Azure Logic App】微软云逻辑应用连接到数据库,执行存储过程并转换执行结果为JSON数据
【Azure Logic App】微软云逻辑应用连接到数据库,执行存储过程并转换执行结果为JSON数据
【Azure Logic App】微软云逻辑应用连接到数据库,执行存储过程并转换执行结果为JSON数据
|
1月前
|
JSON 前端开发 API
【淘系】商品详情属性解析(属性规格详情图sku等json数据示例返回参考),淘系API接口系列
在淘宝(或天猫)平台上,商品详情属性(如属性规格、详情图、SKU等)是商家在发布商品时设置的,用于描述商品的详细信息和不同规格选项。这些信息对于消费者了解商品特性、进行购买决策至关重要。然而,直接通过前端页面获取这些信息的结构化数据(如JSON格式)并非直接暴露给普通用户或开发者,因为这涉及到平台的商业机密和数据安全。 不过,淘宝平台提供了丰富的API接口(如淘宝开放平台API),允许有资质的开发者或合作伙伴通过编程方式获取商品信息。这些API接口通常需要注册开发者账号、申请应用密钥(App Key)和秘钥(App Secret),并遵守淘宝的API使用协议。