ajax实例解析

Ajax是现在前端可以说是不能缺少的一样技术,各种异步操作、局部刷新都要靠它,今天我们就来看点常见的ajax实例吧。

例1:实现一个最简单的ajax实例

// ajax方法
var param = {
    url: ''
    , type: 'get'
    , data:
    {}
    , success: function () {}
    , error: function () {}
, }
var ajax = function (param, callback)
{
    // 创建ajax
    var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
    //对传入的值进行前期主力,包括type/url/data
    var type = (param.type || 'get')
        .toUpperCase();
    var url = param.url;
    if (!url)
    {
        return;
    }
    var data = param.data
        , dataArr = [];
    for (var k in data)
    {
        dataArr.push(k + '=' + data[k]);
    }
    //为了避免取得的是缓存数据,为其添加一个唯一的id
    dataArr.push('=' + Math.random());
    //get还是post。url处理,open()。send()
    if (type === "GET")
    {
        if (callback)
        {
            url = callback(url, data);
        }
        else
        {
            url = url + "?" + dataArr.join("&");
        }
        console.log(url);
        xhr.open(type, url.replace(/\?$/g, ''), true);
        xhr.send();
    }
    else if (type === "POST")
    {
        xhr.open(type, url, true);
        //像表单一样post数据,使用setRequestHeader来添加头部
        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhr.send(dataArr.join("&"));
    }
    //接收请求
    xhr.onreadystatechange = function ()
    {
        //成功
        console.log(xhr.responseText);
        if (xhr.status === 200 || xhr.status === 304)
        {
            var res;
            if (param.success && param.success instanceof Function)
            {
                // 获取字符串形式的响应数据
                res = xhr.responseText;
                if (!isJSON(res))
                {
                    // 把JSON转换成数组
                    // res = JSON.parse(res);
                    param.success.call(xhr, res);
                }
                else
                {
                    res = JSON.parse(res);
                    param.success.call(xhr, res);
                }
            }
        }
        else
        {
            // 失败
            if (param.error && (param.error instanceof Function))
            {
                param.error.call(xhr, res);
            }
        }
    }
}

例2:通过jQuery ajax实现从服务器查询数据,返回给前端并显示至html

Index.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>使用 jQuery validate 表单验证</title>
    <script th:src="@{/scripts/jquery-3.3.1.min.js}"></script>
    <script th:src="@{/scripts/jquery.validate.min.js}"></script>
    <script th:src="@{/scripts/messages_zh.min.js}"></script>
    <script th:src="@{/scripts/user/login.js}"></script>
</head>
<body>
<form id="form1" action="/userLogin">
    <input type="text" id="userName" name="userName"><br>
    <input type="email" id="email" name="email"><br>
    <select id="depertmentId" name="departmentId">
    </select><br>
    <input type="password" id="password" name="password"><br>
    <input type="submit" value="login">
</form>
</body>
</html>

Login.js

function findAllDepts()
{
    $.ajax(
    {
        async: false, //表示请求是否异步处理
        type: "post", //请求类型
        url: "/getDepts", //请求的 URL地址
        dataType: "json", //返回的数据类型
        success: function (data)
        {
            console.log(data); //在控制台打印服务器端返回的数据
            for (var i = 0; i < data.length; i++)
            {
                console.log(data[i].deptId + " " + data[i].deptName);
            }
            $("select[name='depertmentId']")
                .empty();
            $("select[name='depertmentId']")
                .append('<option value="">——请选择——</option>');
            for (var i = 0; i < data.length; i++)
            {
                var html = '<option value="' + data[i].deptId + '">';
                html += data[i].deptName + '</option>';
                $("select[name='departmentId']")
                    .append(html); //将数据显示在html页面
            }
        }
        , error: function (data)
        {
            alert(data.result);
        }
    });
};
$(document)
    .ready(function ()
    {
        findAllDepts(); //页面加载完成就执行该方法
    });

Java后端控制器

package com.njxz.demo.controller;
import com.njxz.demo.domain.Department;
import com.njxz.demo.domain.User;
import com.njxz.demo.service.IUserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
@RestController
public class UserController
{
    @Resource
    private IUserService userService;
    @RequestMapping("/getDepts")
    public List < Department > getDepts()
    { //查找所有部门
        List < Department > depts = userService.findAllDepts();
        return depts;
    }
}

后盾返回的对象类

package com.njxz.demo.domain;
public class Department
{
    private Integer deptId;
    private String deptName;
    public Integer getDeptId()
    {
        return deptId;
    }
    public void setDeptId(Integer deptId)
    {
        this.deptId = deptId;
    }
    public String getDeptName()
    {
        return deptName;
    }
    public void setDeptName(String deptName)
    {
        this.deptName = deptName == null ? null : deptName.trim();
    }
}

以上就是所有的ajax实例了,你对ajax的理解有加深吗?还想查看一些java经典例子的话,请记得关注我们网站了解。

推荐阅读:

ajax跨域请求如何解决?什么是跨域?

ajax是什么?优点缺点是什么?

如何发送ajax请求?ajax请求的五个步骤详解