<!-- 客户端代码实现 --> <!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 type="text/javascript"> //封装共性,提取特性 //保存表单中名字的值(特性) 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);//响应结果不一样的处理方式 }); } //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方法传值 } </script> </body> </html>