前言:
案例在js环境中实现ajax异步的数据交互,功能为表单验证,业务流程如下:
1.输入身份识别码 和 个人身份信息 提交, 会以AJAX 方式下的 GET方式于后台进行交互。根据后台数据返回结果,如数据存在
则提示后,显示个人详细信息。
2.查询人如需修改信息,需要通过解禁键解锁信息框,录入数据后更新。在js原生控制下使用到了多个方法。分别如下:
//getElementsByTagName() 方法返回HTMLCollection对象,该对象类似包含HTML元素的一个数组
var inputEdit = document.getElementsByTagName("input"); //获取所有input标签的集合
var i ;
for(i = 2;i<inputEdit.length-1;i++){
inputEdit[i].attributes.removeNamedItem("disabled"); //attributes 获得标签内的元素集合
}} //removeNamedItem() 移除某个元素属性
3.点击更新数据后,本次切换以AJAX方式下的POST方法想后台完成数据交互。根据后台数据结果,进行弹窗提示。
需要注意的地方有三点:
<1>设置数据传输的表头 setRequestHeader("Content-type","application/x-www-form-urlencoded")
<2>POST方式的数据组成方式不同会导致对应服务端后台获取数据的方式变化:
如果数据变量以字符串的样式,如:data="name="+name+"&age="+age;方式提交的话服务端可直接通过 $_POST['name']的方式获取到传输的数据,处理起来比较简单。
如果数据变量以JS对象的方式发送,需要注意对待发数据进行JS对象转JSON字符串的处理,通过JSON.stringify(data)的转换后,发送的数据,到了服务端仍是不能直接使用的,需要将前端的数据构建成一个键值对发送,此时服务端会获得一个关联数组,同时在服务端需要对此数据进行JSON字符串转换成PHP对象的操作,使用json_decode($_POST['data']) 进行转换,从而得到一个可以在PHP环境下直接使用的对象,对象中的键值对就是表单数据。主要步骤如下:
前端 JS 对象数据 var obj;---> 转码 var json_date= JSON.stringify(obj) --> 构架合适的数据样式---> send("data="+json_data)
服务端 JSON字符串数组 ,即获得前端数据为 ["data"=>{json_data}] -->转码获得PHP对象 $obj =json_decode($_POST['data'])---> 对象元素赋值获得关联数据, ¥obj->name 等。。
<3>功能完善中使用的使用的表单元素序列获取,可以极大的简化对表单每个元素的定位工作,效率比逐一定位表单元素要快,更适合在表单元素较多时候操作使用。
作业效果图:
一、
二、 GET 方式交互验证
三、
四、POST方式交互更新
五
代码实例 前端代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>身份验证-ajax之GET查询+POST修改</title> <style> *{ margin: 0; padding: 0; } body{ background-color:#E9EAED; } .login{ width:450px; margin: 80px auto; padding: 15px; text-align: center; border-radius: 5px; background-color: #FFFFFF; } .content{ display: none; } .login table{ margin: auto; } thead tr th p{ margin: 0 auto; color: #ff4d4d; font-size: 22px; padding-bottom: 10px; margin-bottom: 5px; border-bottom: 2px dashed #b3b3cc; } tbody tr{ padding: 5px 0; height:40px; } tbody hr{ border-bottom:1px dashed #b3b3cc; } tbody tr td:nth-child(1){ text-align: right; width: 100px; padding-right: 5px; } tbody tr td:nth-child(2){ text-align: left; padding-left: 5px; } tbody tr td:nth-child(2) input{ border-radius: 5px; border: 1px solid #b3b3cc; width: 185px; height: 30px; padding: 0 20px; } tfoot button{ color: #ffffff; font-size: 16px; margin-top: 10px; margin-left: 20px; border-radius: 5px; border: 1px solid #b3b3cc; background-color: #4d88ff; width: 320px; height: 40px; } .Info{ display: none; } .show{ display: block; } .Info tfoot button{ color: #ffffff; font-size: 16px; margin-top: 10px; margin-left: 20px; border-radius: 5px; border: 1px solid #b3b3cc; background-color: #4d88ff; width: 150px; height: 40px; }{} </style> </head> <body> <div class="login"> <div class="content show" id="content"> <form action="" method="post" name="login"> <table> <thead> <tr> <th colspan="2"> <p>身份验证</p> </th> </tr> </thead> <tbody> <tr> <td> <label for="loginId">证件号码 :</label> </td> <td> <input type="text" id="loginId" name="loginId" min="11" max="11" value="20190718001" placeholder="11位身份识别码"> </td> </tr> <tr> <td> <label for="userName">个人姓名 :</label> </td> <td> <input type="text" id="userName" name="userName" max="8" value="道无涯" placeholder="仅支持中文姓名,限8个字"> </td> </tr> </tbody> <tfoot> <tr> <td colspan="2"> <button type="button" id="submit_1">立 即 登 录</button> </td> </tr> </tfoot> </table> </form> </div> <div class="Info" id="Info"> <form name="userInfo" action=""> <table> <thead> <tr> <th colspan="2"> <p>身份信息</p> </th> </tr> </thead> <tbody> <tr> <td> <label for="name">姓名 :</label> </td> <td> <input type="text" id="name" name="name" min="6" max="16" disabled> </td> </tr> <tr> <td> <label for="age">年龄 :</label> </td> <td> <input type="text" id="age" name="age" disabled> </td> </tr> <tr> <td> <label for="sex">性别 :</label> </td> <td> <input type="text" id="sex" name="sxe" disabled> </td> </tr> <tr> <td> <label for="work">职业 :</label> </td> <td> <input type="text" id="work" name="work" disabled> </td> </tr> <tr> <td> <label for="address">籍贯 :</label> </td> <td> <input type="text" id="address" name="address" disabled> </td> </tr> <tr> <td> <label for="birthday">出生日期 :</label> </td> <td> <input type="date" id="birthday" name="birthday" disabled> </td> </tr> <tr> <td> <label for="tel">*** :</label> </td> <td> <input type="tel" id="tel" name="tel" placeholder="13845679988" disabled> </td> </tr> <tr> <td> <label for="email">Email :</label> </td> <td> <input type="email" id="email" name="email" placeholder="973245277@qq.com" disabled> <input type="hidden" id="userId" name="userId"> </td> </tr> </tbody> <tfoot> <tr> <td colspan="2"> <button type="button" id="submit_2">修 改 信 息</button> <button type="button" id="submit_3">确 认 保 存</button> </td> </tr> </tfoot> </table></form> </div> </div> <script> // ************* AJAX应用之GET方式 ********************************** // 【login登录表】 button 元素 定位 var but_login = document.getElementById("submit_1"); //获取 login 表单 var login = document.forms.namedItem('login'); // login 表单按钮事件监听触发 but_login.addEventListener("click",getLogin,false); //but_login 监听触发的事件 AJAX(GET方式提交) 用途:输入证件号 和对应的姓名 查询出身份信息 function getLogin() { var id = login.loginId.value; var name =login.userName.value; //实例化 Ajax var xhr = new XMLHttpRequest(); // 存储函数,当readyState属性改变时,就会调用该函数 xhr.onreadystatechange = function () { //readyState 响应就绪 和Status 响应完成 200 OK 的情况下执行 //监听 if (xhr.readyState == 4 && xhr.status == 200) { var res = JSON.parse(xhr.responseText); var msg = null; if (res.code == "0") { alert(res.msg); msg = res.data; userInfo.name.setAttribute("value",msg['name']); userInfo.age.setAttribute("value",msg['age']); userInfo.sex.setAttribute("value",msg['sex']); userInfo.work.setAttribute("value",msg['work']); userInfo.address.setAttribute("value",msg['address']); userInfo.birthday.setAttribute("value",msg['birthday']); userInfo.tel.setAttribute("value",msg['tel']); userInfo.email.setAttribute("value",msg['email']); userInfo.userId.setAttribute("value",msg['id']); var content =document.getElementById("content"); var Info =document.getElementById("Info"); content.classList.remove("show"); Info.classList.add("show"); } else { alert(res.msg); } } }; //设置GET 请求参数 xhr.open("GET","/index/info/user_find.php?id="+id+"&name="+name,true); //发送请求 xhr.send(); } // ************ AJAX应用之POST方式 ********************************** //【userInfo信息表】 button 元素 定位 var but_edit = document.getElementById("submit_2"); var but_save = document.getElementById("submit_3"); //获取 userInfo 表单 var userInfo = document.forms.namedItem("userInfo"); // userInfo表单按钮事件监听触发 but_edit.addEventListener("click",edit,false); but_save.addEventListener("click",modifyInfo,false); // 激活表单禁用效果 function edit(){ //getElementsByTagName() 方法返回HTMLCollection对象,该对象类似包含HTML元素的一个数组 var inputEdit = document.getElementsByTagName("input"); var i ; for(i = 2;i<inputEdit.length-1;i++){ inputEdit[i].attributes.removeNamedItem("disabled"); } } // but_save 监听触发的事件 AJAX(POST方式提交) 用途: 更新用户数据 function modifyInfo(){ var xhr =new XMLHttpRequest(); xhr.onreadystatechange = function () { if(xhr.readyState==4&&xhr.status==200){ var msg = JSON.parse(xhr.responseText); if (res.code == "0") { alert(res.msg); var content =document.getElementById("content"); var Info =document.getElementById("Info"); content.classList.add("show"); Info.classList.remove("show"); } else { alert(res.msg); } } }; //设置参数 xhr.open("POST","/index/info/user_edit.php",true); xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); // 更新数据 var data ={ name: userInfo.name.value, age: userInfo.age.value, sex: userInfo.sex.value, work: userInfo.work.value, address: userInfo.address.value, birthday: userInfo.birthday.value, tel: userInfo.tel.value, email: userInfo.email.value, id: userInfo.userId.value }; //JS对象转JSON字符串 var json_data = JSON.stringify(data); //JSON数据发送服务端 xhr.send('data='+json_data); // var type ="POST"; // var data ="type="+type+"&name="+userInfo.name.value+"&age="+userInfo.age.value+ // "&sex="+userInfo.sex.value+"&work=" +userInfo.work.value // +"&address="+userInfo.address.value+"&birthday="+userInfo.birthday.value // +"&tel="+userInfo.tel.value+"&email="+userInfo.email.value+"&userId="+userInfo.userId.value; // xhr.send(data); } </script> </body> </html>
点击 "运行实例" 按钮查看在线实例
服务器后台代码 1 查询
<?php $userInfoArr =[ ["id"=>"001","name"=>"道无涯","sex"=>"1","age"=>"99","address"=>"天池","loginId"=>"20190718001","work"=>"隐者","tel"=>"1380000001","email"=>"wuyan@php.cn","birthday"=>"1901-05-08"], ["id"=>"002","name"=>"武痴","sex"=>"1","age"=>"38","address"=>"天山","loginId"=>"20190718002","work"=>"打手","tel"=>"1380000002","email"=>"wuchi@php.cn","birthday"=>"1980-09-09"], ["id"=>"003","name"=>"妖姬","sex"=>"0","age"=>"22","address"=>"苗疆","loginId"=>"20190718003","work"=>"法师","tel"=>"1380000003","email"=>"yaoji@php.cn","birthday"=>"1990-11-07"], ["id"=>"004","name"=>"赤炼","sex"=>"0","age"=>"14","address"=>"峨眉","loginId"=>"20190718004","work"=>"歌姬","tel"=>"1380000004","email"=>"chilian@php.cn","birthday"=>"2003-06-30"] ]; $userName= $_GET['name']; $loginId =$_GET['id']; if( !empty($userName) && !empty($loginId)){ $userInfo = null; foreach ($userInfoArr as $val ) { if($userName == $val['name'] && $loginId == $val['loginId'] ){ $userInfo = $val; exit(json_encode(Array("code"=>"0","msg"=>"您所需要的信息已查出,请稍后","data"=>$userInfo))); } } if($userInfo==null){ exit(json_encode(Array("code"=>"1","msg"=>"您所检索的数据不存在"))); } }
点击 "运行实例" 按钮查看在线实例
服务器后台代码 2 更新
<?php $userInfoArr =[ ["id"=>"001","name"=>"道无涯","sex"=>"1","age"=>"99","address"=>"天池","loginId"=>"20190718001","work"=>"隐者","tel"=>"1380000001","email"=>"wuyan@php.cn","birthday"=>"1901-05-08"], ["id"=>"002","name"=>"武痴","sex"=>"1","age"=>"38","address"=>"天山","loginId"=>"20190718002","work"=>"打手","tel"=>"1380000002","email"=>"wuchi@php.cn","birthday"=>"1980-09-09"], ["id"=>"003","name"=>"妖姬","sex"=>"0","age"=>"22","address"=>"苗疆","loginId"=>"20190718003","work"=>"法师","tel"=>"1380000003","email"=>"yaoji@php.cn","birthday"=>"1990-11-07"], ["id"=>"004","name"=>"赤炼","sex"=>"0","age"=>"14","address"=>"峨眉","loginId"=>"20190718004","work"=>"歌姬","tel"=>"1380000004","email"=>"chilian@php.cn","birthday"=>"2003-06-30"] ]; $user = json_decode($_POST['data']); $name = $user->name; $age = $user->age; $sex = $user->sex; $work = $user->work; $address = $user->address; $birthday = $user->birthday; $tel = $user->tel; $email = $user->email; $id = $user->id; foreach ($userInfoArr as $a=>$val ){ if($id == $val["id"]){ $userInfoArr[$a]["name"]= $name; $userInfoArr[$a]["age"]= $age; $userInfoArr[$a]["sex"]= $sex; $userInfoArr[$a]["work"]= $work; $userInfoArr[$a]["address"]= $address; $userInfoArr[$a]["birthday"]= $birthday; $userInfoArr[$a]["tel"]= $tel; $userInfoArr[$a]["email"]= $email; exit(json_encode(Array("code"=>"0","msg"=>"数据更新成功。"))); } } exit(json_encode(Array("code"=>"1","msg"=>"数据更新失败。")));
点击 "运行实例" 按钮查看在线实例