AJAX front-end basis of

AJAX

What is AJAX, simply, is the use of asynchronous JavaScript natural features, the use of asynchronous requests background information, so as to achieve the effect can not refresh the page partial page update.

Native AJAX

JavaScript, AJAX depends on the XMLHttpRequestobject.

  • Js also be used to create new objects:new XMLHttpRequest()
  • onreadystatechangeListening to events, changes in monitor requests and responses, can be understood as the callback function callback (onreadystatechange event is triggered 5 (0 - 4), corresponding to each change of readyState)
  • readyState: request state value, the state of the XMLHttpRequest there. Varies from 0 to 4:
    • 0: Request uninitialized
    • 1: The server connection has been established
    • 2: The request receiving
    • 3: Request Processing
    • 4: request has been completed, and the response is ready
  • status: Response status values: 200: success response 404
  • open(method,url,async): Predetermined request information, address, synchronous / asynchronous:
    • method: type of the request; the GET or POST
    • url: location of the file on the server
    • async: true (asynchronous) or false (sync) (synchronization is unnecessary to provide a callback function)
  • send(String)send request. When the get, open the good fight url parameter, send the parameter does not pass; when post, open no parameters, send afferent parameters (in this case requires the use of a method provided serHeader Content-Type attribute)
  • responseTextTo obtain a response result character string. (ResponseXML) to get a response as XML

The last native AJAX detection username Demo:


Native AJAX

Front-end HTML:

<h2>用户注册</h2>
用户名:
<input type="text" name="userName" id="userName"> <span id="info"></span>

Js:

//绑定失去焦点事件
document.getElementById("userName").onblur = function (ev) {
    var userName = this.value;
    var xhr = new XMLHttpRequest();
    //绑定回调函数
    xhr.onreadystatechange = function (ev1) {
        if (xhr.readyState === 4 && xhr.status === 200){
            document.getElementById('info').innerText = xhr.responseText;
        }
    };
    xhr.open("get", '/AjaxServlet?userName=' + userName, true);
    xhr.send();
};

servlet background:

String userName = request.getParameter("userName");
response.setContentType("text/plain;charset=utf-8");
if ("admin".equals(userName)){//这里为了简单不从数据库获取了,直接使用固定的"admin"检验
    response.getWriter().println("用户名已存在");
}else {
    response.getWriter().println("用户名可用");
}

JQuery encapsulated AJAX

Of native JQuery AJAX the package, more convenient to use.

Request method grammar Explanation
GET request $.get(url,[data],[callback],[type]) With [] is optional
POST request $.post(url,[data],[callback],[type]) With [] is optional
AJAX requests $.ajax({settings})
GET signature $.get({settings}) jQuery3.0 get new method
POST signature $.post({settings}) jQuery3.0 new post method

Get/Post

$.get(url,[data],[callback],[type])
$.post(url,[data],[callback],[type])

parameter Explanation Required
url Request address essential
data Request parameters sent to the server side, formats:
Mode 1: key = value & key = value
Second way: {key: value, key: value ...}
Optional
callback Callback: function is triggered when the request is successful Optional
type Return parameters Type: Value may be xml, html, script, json, text, _defaul the like, the default text Optional

The use JQuery get / post method performed AJAX visit:

$('#userName').blur(function () {
    //看var不舒服换成了let
    let userName = $(this).val();
    $.get('/AjaxServlet', {userName:userName},function (result) {
        $('#info').text(result)
    });
});
//get/post用法一样

The following case of post, other general usage get

  • Can not use the cache files (files or update the database on the server) - to submit the form data
  • Send large amounts of data to the server (POST does not limit the amount of data) --- file uploads

Using JQuery's ajax method performed AJAX visit:
$.ajax({settings})

setting parameters:

Property name description
url url address request
async true asynchronous, false synchronization (the default is true)
data Data sent to the server, the key can be made in the form, it may be in the form of an object js
type Request mode (the default is get)
dataType Expected return data type (xml, html, script, json, text, _default)
success Successful request a callback function
error The request failed callback function

ajax method for data requests:


AJAX method

$("#userName").blur(function () {
    let userName = $(this).val();
    $.ajax({
        url:"/ajaxDemoServlet",
        data:{"userName":userName,"age":4},
        async:true,
        type:"GET",
        dataType:"text",
        success:function (result) {
            $("#info").text(result);
        },
        error:function (errorRes) {
            alert("出现异常了")
        }
    })
});

JQuery 3.0 New method: $.get({settings}), $.post({settings})usage and ajax method like this:


Get new method

$("#userName").blur(function () {
    let userName = $(this).val();
    $.get({
        url:"/ajaxDemoServlet",
        data:{"userName":userName,"age":4},
        dataType:"text",
        success:function (result) {
            //处理正常的响应
            $("#info").text(result);
        },
        error:function (errorRes) {
            alert("出现异常了")
        }
    })
});

JSON

Json three expressions:

Types of the way description
Object type: {K:V,K:V} Represents an object, there are more attribute names and values
Array / set type: [V1,V2,V3] It represents an array of objects, which may be any type of element
Mixed Type: [{K:V, K:V}, {K:V, K:V}]or{K:[V, V, V]} On behalf of each element in the array is an object, a property value of an object is an array

Java, Json object system conversion

Use Jackson

Add Dependency (three packages can be added manually jackson-databind.jar jackson-core.jar jackson-annotation.jar, or directly maven):

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.9</version>
</dependency>

Json object into a string :
rely on ObjectMapperthe object, call the writeValueAsString(Object o)method to the objects, arrays, collections into Json.

Json string into the object
calling ObjectMapperthe public <T> T readValue(String content, Class<T> valueType)method.

Use FastJson tools

The main use toJSONStringand parseObjectserialization and deserialization operation is omitted here.


AJAX user name authentication Demo

Front page:

<input type="text" id="inputUserName" name="username" class="form-control" placeholder="用户名" required autofocus>
<span id="info"></span>

Complete code:


Full HTML Code

Use the Bootstrap framework, modify the JS file location yourself.

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come test in the head; any other head content must come *after* these tags -->
    <meta name="description" content="">
    <meta name="author" content="">

    <title>AJAX Demo</title>

    <!-- Bootstrap core CSS -->
    <link href="/css/bootstrap.css" rel="stylesheet">

    <!-- Custom styles for this template -->
    <link href="/css/login.css" rel="stylesheet">

</head>

<body>

<div class="container">

    <form class="form-signin" action="/login" method="POST">
        <div class="text-center">
            <h2 class="form-signin-heading">登录页面</h2>
        </div>
        <label for="inputUserName" class="sr-only">用户名</label>
        <input type="text" id="inputUserName" name="username" class="form-control" placeholder="用户名" required autofocus>
        <span id="info"></span>
        <label for="inputPassword" class="sr-only">密码</label>
        <input type="password" id="inputPassword" name="password" class="form-control" placeholder="密码" required>
        <div>
            <input type="text" name="checkCode" class="form-control" style="width: 184px;float: left;"
                   placeholder="请输入验证码">
            <img id="captcha" style="width: 84px;margin-left: 29px;" src="/CodeServlet" alt="验证码"
                 onclick="changeImg(this)">
        </div>
        <div class="checkbox">
            <label>
                <input type="checkbox" value="remember-me"> 记住账号密码
            </label>
        </div>
        <button class="btn btn-lg btn-primary btn-block" type="submit">登录</button>
    </form>

</div> <!-- /container -->

</body>
<script src="/js/jquery.js"></script>
<script src="/js/myjs/login.js"></script>
</html>

JavaScript binding events:

//使用JQuery绑定
$('#inputUserName').blur(function () {
    //获取输入的userName
    let userName = $(this).val();
    if (userName === "") {
        $('#info').html('<font color="red">请输入用户名</font>');
    } else {
        //AJAX异步请求数据
        $.get('/CheckNameServlet', {userName: userName}, function (result) {
            //这里需要把字符串转化为boolean
            if (!JSON.parse(result.flag)) {
                $('#info').html('<font color="red">用户名已存在</font>');
            } else {
                $('#info').html('<font color="green">✔</font>');
            }
            console.log(result);
        },'json')
    }
});

Then the rear end of the control layer:

@WebServlet("/CheckNameServlet")
public class CheckNameServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/plain;charset=utf-8");
        String userName = request.getParameter("userName");
        UserService us = new UserService();
        boolean flag = us.queryUserByName(userName);
        Map<String,String> map = new HashMap<>();
        map.put("flag", String.valueOf(flag));//返回布尔值好像还不如返回 0 或 1
        //这里使用了Jackson转化为Json
        response.getWriter().print(new ObjectMapper().writeValueAsString(map));
        //System.out.println(map);
    }
}

Background business layer:

public class UserService {
    public boolean queryUserByName(String name){
        UserDao ud = new UserDao();
        List<User> list = ud.queryUserByName(name);
        if (list!=null && list.size()>0){
            return false;
        }else {
            return true;
        }
    }
}

Background persistence layer:

public class UserDao {
    public List<User> queryUserByName(String name) {
        JdbcTemplate jt = DataSourceUtil.getJdbcTemplate();
        String sql = "select * from t_user where username = ?";//这个sql不太好,查询了太多无用数据
        return jt.query(sql, new BeanPropertyRowMapper<>(User.class), name);
    }
}

final effect:

Initial page:

The initial page

When without entering a user name box loses focus:

lose focus

Enter the user name already exists:

Username already exists

Username available:

Username available


So far, AJAX simple introductions

Guess you like

Origin www.cnblogs.com/lixin-link/p/11229177.html