<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery_封装ajax请求</title>
</head>
<body>
<button id = "btn">click</button>
用户名:<input type = "text" id = "username" />
<div id = "div01">
</div>
<script type="text/javascript">
function $( s ){
if( typeof s == "string" ){
//第一个字符是 # 是 则认为 参数s 是id选择器
if( s.charAt(0) == "#" ){
// substring 获取 id ,根据 id 获取元素
//domObj 无 var 修饰 成为全局变量
domObj = document.getElementById( s.substring(1) );
//$() 当作一个类 返回该类的对象,通过该对象可以调用该类的 html 方法
return new $();
}
}
if( typeof s == "function" ){
//if s 是function 则将 s 付给 window.onload 在 页面加载完毕时执行 函数 s
window.onload = s;
}
this.html = function( htmlStr ){
domObj.innerHTML = htmlStr;
}
this.value = function(){
return domObj.value;
}
this.click = function ( fun ) {
// $("#btn")返回的是 $()对象,该对象无onclick方法因此为该类添加click方法代替 $("#btn").onclick
domObj.onclick = fun;
}
//静态方法,发送ajax request 参数为一个json对象
$.ajax = function( jsonArgs ) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (this.status == 200) {
//var jsonObj = JSON.parse(this.responseText);
jsonArgs.success(this.responseText);
}
}
}
if (jsonArgs.type.toUpperCase() == "POST") {
xhr.open("POST", jsonArgs.url, jsonArgs.async);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(jsonArgs.data);
}
if (jsonArgs.type.toUpperCase() == "GET") {
xhr.open("GET", jsonArgs.url + "?" + jsonArgs.data, jsonArgs.async);
xhr.send();
}
}
}
//new 过之后,其静态方法才能 生效
new $();
$("#btn").click(
function(){
var username = $("#username").value();
//发送 ajax 请求
$.ajax(
{
type: "POST",
url: "/ajax/request",
data: "username=" + username,
async: true,
success: function (json) {
$("#div01").html(json);
}
}
);
}
);
</script>
</body>
</html>
controller
package com.example.demo07.controller;
import com.alibaba.fastjson.JSON;
import com.example.demo07.dto.Book;
import com.example.demo07.service.BookService;
import com.example.demo07.service.IBookService;
import com.example.demo07.service.UserService;
import com.example.demo07.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/ajax")
public class AJAX {
@RequestMapping("/request")
public String ajaxTest( @RequestParam String username){
return username;
}
}
填入 用户名
click