ajax工具类代码:
注意:使用前需要引入jquery
(function () {
var $ax = function (type,url, success, error) {
this.url = url;
this.type = type;
this.data = {};
this.dataType = "json";
this.async = false;
this.success = success;
this.error = error;
};
$ax.prototype = {
start : function () {
var me = this;
if (this.url.indexOf("?") == -1) {
this.url = this.url + "?jstime=" + new Date().getTime();
} else {
this.url = this.url + "&jstime=" + new Date().getTime();
}
$.ajax({
type: this.type,
url: this.url,
dataType: this.dataType,
async: this.async,
data: this.data,
beforeSend: function(data) {
},
success: function(data) {
me.success(data);
},
error: function(data) {
me.error(data);
}
});
},
set : function (key, value) {
if (typeof key == "object") {
for (var i in key) {
if (typeof i == "function")
continue;
this.data[i] = key[i];
}
} else {
this.data[key] = (typeof value == "undefined") ? $("#" + key).val() : value;
}
return this;
},
setData : function(data){
this.data = data;
return this;
},
clear : function () {
this.data = {};
return this;
}
};
window.$ax = $ax;
} ());
测试代码:
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2019/10/15
Time: 11: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="js/jquery.min.js"></script>
<script src="js/ajax-object.js"></script>
</head>
<body>
<button id="btn" onclick="del()">查询</button>
<script>
function del(){
var ajax = new $ax("get","http://localhost:8089/book/getBookById", function (data) {
alert(data);
}, function (data) {
});
ajax.set("id",2);
ajax.start();
};
</script>
</body>
</html>
java后端代码:
package com.xiaomin.controller;
import com.xiaomin.dao.BookMapper;
import com.xiaomin.pojo.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
/**
* <p>
* 前端控制器
* </p>
*
* @author wangxm
* @since 2019-08-12
*/
@Controller
@RequestMapping("/book")
public class BookController {
@Autowired
private BookMapper bookMapper;
/**
* 查询所有图书信息
* @return
*/
@GetMapping("/getBoook")
@ResponseBody
public List<Book> getBook(){
List<Book> books = bookMapper.selectList(null);
return books;
}
@GetMapping("/getBookById")
@ResponseBody
public Book getBookById(Integer id){
Book book = bookMapper.selectById(id);
return book;
}
}