Ajax异步操作和Json的相关学习

Posted 肖帆咪

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Ajax异步操作和Json的相关学习相关的知识,希望对你有一定的参考价值。

Ajax


Ajax 全称为:“Asynchronous javascript and XML”(异步 JavaScript和 XML),使用 Ajax,我们可以无刷新状态更新页面,并且实现异步提交,提升了用户体验。

Ajax其实质是利用浏览器提供的一个特殊的对象(XMLHttpRequest)异步地向服务器发送请求,服务器返回部分数据,浏览器让你去利用这些数据对页面做部分的更新,整个过程,页面无刷新,不打断用户的操作

同步

目前与服务器端的交互方式是同步,当客户端与服务器交互时,客户端就不能进行其他操作,只能等待服务器端的响应,会刷新页面.

异步(不同步):

当客户端正在进行正常操作时,还可以同时与服务器进行交互,服务器向客户端响应信息,将信息更新到网页局部,整个过程页面不刷新.

创建XMLHttpRequest对象

•XMLHttpRequest对象:发送请求到服务器并获得返回结果

•所有现代浏览器 都内建了 XMLHttpRequest 对象,通过一行简单的 JavaScript 代码,我们就可以创建 XMLHttpRequest 对象。

​ xmlhttp=new XMLHttpRequest();

XMLHttpRequest

方法名说 明
open(method,URL,async)建立与服务器的连接 method参数指定请求的HTTP方法,典型的值是GET或POST URL参数指定请求的地址 async参数指定是否使用异步请求,其值为true或false
send(content)发送请求 content参数指定请求的参数
setRequestHeader(header,value)设置请求的头信息
就绪状态码说 明
0XMLHttpRequest对象没有完成初始化
1XMLHttpRequest对象开始发送请求
2XMLHttpRequest对象的请求发送完成
3XMLHttpRequest对象开始读取响应,还没有结束
4XMLHttpRequest对象读取响应结束
状态码说 明
200服务器响应正常
400无法找到请求的资源
403没有访问权限
404访问的资源不存在
500服务器内部错误

Get方式

xmlhttp.open(“GET”,“testServlet?name=”+userName,true);
xmlhttp.send(null);

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script type="text/javascript">
        function checkAccount(account) {
            //1.创建XMLHttprequest对象
            var httpObj = new XMLHttpRequest();
            //2.使用XMLHTTPRequest对象向服务器发送异步请求
            httpObj.open("get","${path}/ajax1",true);//封装请求信息
            httpObj.send("account="+account);
            //3.从XMLHttpRequest对象中取出响应的数据
            //当请求发送之后,会触发onreadystatechange事件
            httpObj.onreadystatechange=function (){
                //status Http的状态码,200表示响应正常
                if (httpObj.readyState==4&&httpObj.status==200){
                    //responseText获取响应文本内容
                    document.getElementById("msgid").innerHTML = httpObj.responseText;
                }
            }
        }
    </script>
</head>
<body>
<input type="text" name="account" onblur="checkAccount(this.value)" ><span id="msgid"></span>
<input type="password" name="password">
</body>
</html>

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;
import java.io.PrintWriter;

@WebServlet(name = "ajax1", urlPatterns = "/ajax1")
public class AjaxServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String account = req.getParameter("account");
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        if (account.equals("admin")){
            out.print("账号已存在");//向异步请求做出响应
        }else{
            out.print("√");
        }
    }
}

Post方式

xmlhttp.open(“POST”,“testServlet”,true);
POST方式需要自己设置http的请求头
xmlhttp.setRequestHeader(“Content-Type”,“application/x-www-form-urlencoded”);
POST方式发送数据
xmlhttp.send(“name=”+userName);

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script type="text/javascript">
        function checkAccount(account) {
            //1.创建XMLHTTPRequest对象
            var httpObj = new XMLHttpRequest();
            //2.使用XMLHTTPRequest 对象向服务器发送异步请求
            httpObj.open("post","${path}/ajax1?account="+account,true);//封装请求信息
            //设置请求头,内部的提交格式为表单的默认格式
            httpObj.setRequestHeader("content-type","applicationCache/x-www-form-urlencoded")
            httpObj.send("account="+account+"&age=23");//信息放在请求体中
            //3.从XMLHTTPRequest对象取出响应的数据
            //当请求发送之后,会触发onreadystatechange事件
            httpObj.onreadystatechange=function (){
                if (httpObj.readyState==4&&httpObj.status==200){
                    document.getElementById("msgid").innerHTML = httpObj.responseText;
                }
            }
        }
    </script>
</head>
<body>
<%--
enctype="multipart/form-data"提交文件
applicationCache/x-www-form-urlencoded 表单默认的提交方式  键=&=--%>
<input type="text" name="account" onblur="checkAccount(this.value)" ><span id="msgid"></span>
<input type="password" name="password">
</body>
</html>

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;
import java.io.PrintWriter;

@WebServlet(name = "ajax1", urlPatterns = "/ajax1")
public class AjaxServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String account = req.getParameter("account");
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        if (account.equals("admin")){
            out.print("账号已存在");
        }else{
            out.print("√");
        }
    }
}

Json

jar包下载地址:https://mvnrepository.com/artifact/com.google.code.gson/gson

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式(特定格式的字符串)

–数据在键值对中 User --> {name:jim,age:23}

–数据由逗号分隔 List —> [ {name:jim,age:23}, {name:jim,age:23}]

JSON 键值对是用来保存 JS 对象的一种方式,和 JS 对象的写法也大同小异,键/值对组合中的键名写在前面并用双引号 “” 包裹,使用冒号 : 分隔,然后紧接着值:

{“firstName”: “John”,age:23,…} \\

[{“name”:”value”,”sex”:””},{“name”:”value”,”sex”:””},{“name”:”value”,”sex”:””}

在异步交换数据时,java对象不能直接被传递给js,所以需要先把java对象转换为JSON格式字符串,把字符串响应给客户端,再由客户端将JSON字符串转换为js对象即可(
$.parseJSON(jsonstr) )。

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script type="text/javascript" src="${path}/js/jquery.1.8.3.min.js"></script>
    <script type="text/javascript">
        function searchUser() {
            var user = document.getElementById("userId").value;
            var httpObj = new XMLHttpRequest();
            httpObj.open("get","${path}/ajax2?user="+user,true);
            httpObj.send();
            httpObj.onreadystatechange=function () {
                if (httpObj.readyState==4&&httpObj.status==200)
                    //json格式的字符串解析为javaScript对象
                    var jsobj = $.parseJSON(httpObj.responseText);
                    document.getElementById("shouid").innerText = jsobj.name+":"+jsobj.age;
            }
        }
    </script>
</head>
<body>
<input type="text" id="userId">
<input type="button" value="查询" onclick="searchUser()">
<div id="shouid">

</div>
</body>
</html>

servlet

import com.ff.bean.User;
import com.google.gson.Gson;

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;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "ajax2", urlPatterns = "/ajax2")
public class AjaxServlet2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String user = req.getParameter("user");
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        //省略数据库查询
        User user = new User();
        user.setName(user);
        user.setAge(21);
       

        //先把java对象转为json格式的字符串
        //String s = "{name:"+user1.getName()+",age:"+user1.getAge()+"}";
        Gson gson = new Gson();
        String s = gson.toJson(user1);
        System.out.println(s);
        out.print(s);
    }
}

异步查询多条数据

import com.ff.bean.User;
import com.google.gson.Gson;

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;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "ajax2", urlPatterns = "/ajax2")
public class AjaxServlet2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String user = req.getParameter("user");
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        //省略数据库查询
        User user1 = new User();
        user1.setName(user);
        user1.setAge(21);
        User user2 = new User();
        user2.setName(user);
        user2.setAge(22);
        User user3 = new User();
        user3.setName(user);
        user3.setAge(23);
        List<User> list = new ArrayList<>();
        list.add(user1);
        list.add(user2);
        list.add(user3);
        Gson gson = new Gson();
        String s = gson.toJson(list);
        System.out.println(s);
        out.print(s);

    }
}

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script type="text/javascript" src="${path}/js/jquery.1.8.3.min.js"></script>
    <script type="text/javascript">
        function searchUser() {
            var user = document.getElementById("userId").value;
            var httpObj = new XMLHttpRequest();
            httpObj.open("get", "${path}/ajax2?user=" + user, true);
            httpObj.send();
            httpObj.onreadystatechange = function () {
                if (httpObj.readyState == 4 && httpObj.status == 200) {
                    //json格式的字符串解析为javaScript对象
                    var jsobjs = $.parseJSON(httpObj.responseText);
                    var str = "";
                    for (i = 0; i < jsobjs.length; i++) {
                        str += jsobjs[i].name + ":" + jsobjs[i].age + "<br/>";
                    }
                    document.getElementById("shouid").innerHTML = str;
                }
            }
        }
    </script>
</head>
<body>
<input type="text" id="userId">
<input type="button" value="查询" οnclick="searchUser()">
<div id="shouid">

</div>
</body>
</html>

Jquery实现AJAX-$.get() 和 $.post()

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script type="text/javascript" src="${path}/js/jquery.1.8.3.min.js"></script>
    <script type="text/javascript">
        function checkAccount(account) {
           /* $.get("${path}/ajax1",{account:account},function (res) {
                $("#msgid").html(res);
            }) */
            $.post("${path}/ajax1",{account:account},function (res) {
                $("#msgid").html(res);
            })
        }
    </script>
</head>
<body>
<input type="text" name="account" onblur="checkAccount(this.value)" ><span id="msgid"></span>
<input type="password" name="password">
</body>
</html>

以上是关于Ajax异步操作和Json的相关学习的主要内容,如果未能解决你的问题,请参考以下文章

ajax 异步请求,json前台后台交互

前端面试题之手写promise

Ajax学习笔记

AJAX相关JS代码片段和部分浏览器模型

Ajax异步请求

Django——Ajax相关