1.在static目录下新建一个js目录,在js目录中增加一个名为ajax.js的文件。
将get办法和post办法的ajax共性提取到ajax.js文件,具体代码如下:
//封装共性,提取个性//Get办法的共性如下:function doAjaxGet(url,params,callback){//1.基于dom事件创立XHR对象const xhr=new XMLHttpRequest();//2.设置XHR对象监听状态xhr.onreadystatechange=function(){//onreadystatechange存储函数,每当readyState属性扭转时,就会调用该函数 if(xhr.readyState==4&&xhr.status==200){ callback(xhr.responseText); }}//3.创立与服务端的连贯xhr.open("GET",`${url}?${params}`,true);//4.发送异步申请实现与服务端的通信xhr.send(null);//get申请send办法传值} //Post办法的共性如下:function doAjaxPost(url,params,callback){ const xhr=new XMLHttpRequest(); xhr.onreadystatechange=function(){ if(xhr.readyState==4&&xhr.status==200){ callback(xhr.responseText); } } xhr.open("POST",url,true); //应用post申请要设置申请头(规定) xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //4.发送异步申请实现与服务端的通信 xhr.send(params);//Post申请send办法传值}
2.在html中引入改js文件,通过增加<script></script>标签引入js文件,具体代码如下:
<script type="text/javascript" src="/js/ajax.js"></script>
客户端代码:
<!-- 客户端代码实现 --><!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title></head><body><!-- html要害表单元素设计 --><h1>The Ajax 03 Page</h1><!-- 该标签的作用是把表单中的相干控件集中起来,造成一个控件组 --><fieldset> <!--该标签用于定义fieldset标签控件组下的题目 --> <legend>Ajax 表单申请</legend> <form> <input type="text" name="name" id="nameId" onblur="doCheck()" onfocus="doClear()"> <input type="button" onclick="doSave()" value="save"> </form> <span id="result"></span></fieldset><!--增加JS要害业务代码 --><!-- script标签用于定义客户端脚本 script元素既能够蕴含脚本语句,也能够通过 src 属性指向内部脚本文件。--><script type="text/javascript" src="/js/ajax.js"></script><script type="text/javascript">//检测名字是否曾经存在 function doClear(){ //示意能向id为result的对象插入“”内容 document.getElementById("result").innerHTML="";} //Get办法的个性function doCheck(){ //1.定义申请的url const url="/doCheck"; //2.定义申请参数 let name=document.forms[0].name.value; let params=`name=${name}`; //3.发送ajax-get申请 doAjaxGet(url,params,function(result1){ document.getElementById("result").innerHTML=`${result1}`; });}//保留表单中名字的值function doSave(){ //1.定义申请的url const url="/doSave"; //2.定义申请参数 let name=document.forms[0].name.value; let params=`name=${name}`; //3.发送ajax-get申请 doAjaxPost(url,params,function(result1){ alert(result1);//响应后果不同的解决形式 });} </script></body></html>
服务端代码:
package com.cy.ajaxcontroller;import java.util.ArrayList;import java.util.List;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;//这是一个服务端,用来解决客户端的申请@Controller@RequestMapping("/")public class AjaxController { private List<String> names=new ArrayList<String>(); //如果这是存储数据的表 @RequestMapping("doSave") @ResponseBody //将客户端申请的数据name写入到names对应的汇合 public String doSave(String name){ System.out.println("name="+name); names.add(name); return name+"save ok"; } @RequestMapping("doCheck") @ResponseBody //通过此办法测验名字是否曾经存在 public String doCheck(String name) { if(names.contains(name)) return "名字:"+name+"曾经存在,请抉择其余名字"; return "名字:"+name+"不存在,能够注册"; }}
浏览器成果: