Ajax 传递JSON实例代码
程序员文章站
2022-06-24 16:29:36
前面的话
虽然ajax全称是asynchronous javascript and xml。但目前使用ajax技术时,传递json已经成为事实上的标准。因为相较于xm...
前面的话
虽然ajax全称是asynchronous javascript and xml。但目前使用ajax技术时,传递json已经成为事实上的标准。因为相较于xml而言,json简单且方便。本文将上一篇中的实例进行改写,以json的方式来进行数据传递
前端页面
<!-- 前端页面 --> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>document</title> <style> body{font-size: 20px;margin: 0;line-height: 1.5;} select,button,input{font-size: 20px;line-height: 1.5;} </style> </head> <body> <h2>员工查询</h2> <label>请输入员工编号:</label> <input type="text" id="keyword"> <button id="search">查询</button> <p id="searchresult"></p> <h2>员工创建</h2> <form id="postform"> <label>请输入员工姓名:</label> <input type="text" name="name"><br> <label>请输入员工编号:</label> <input type="text" name="number"><br> <label>请输入员工性别:</label> <select name="sex"> <option value="男">男</option> <option value="女">女</option> </select><br> <label>请输入员工职位:</label> <input type="text" name="job"><br> <button id="save" type="button">保存</button> </form> <p id="createresult"></p> <script> /*get*/ //查询 var osearch = document.getelementbyid('search'); //get方式添加数据 function addurlparam(url,name,value){ url += (url.indexof("?") == -1 ? "?" : "&"); url +=encodeuricomponent(name) + "=" + encodeuricomponent(value); return url; } osearch.onclick = function(){ //创建xhr对象 var xhr; if(window.xmlhttprequest){ xhr = new xmlhttprequest(); }else{ xhr = new activexobject('microsoft.xmlhttp'); } //异步接受响应 xhr.onreadystatechange = function(){ if(xhr.readystate == 4){ if(xhr.status == 200){ //实际操作 var data = json.parse(xhr.responsetext); if(data.success){ document.getelementbyid('searchresult').innerhtml = data.msg; }else{ document.getelementbyid('searchresult').innerhtml = '出现错误:' +data.msg; } }else{ alert('发生错误:' + xhr.status); } } } //发送请求 var url = 'service.php'; url = addurlparam(url,'number',document.getelementbyid('keyword').value); xhr.open('get',url,true); xhr.send(); } /*post*/ //创建 var osave = document.getelementbyid('save'); //post方式添加数据 function serialize(form){ var parts = [],field = null,i,len,j,optlen,option,optvalue; for (i=0, len=form.elements.length; i < len; i++){ field = form.elements[i]; switch(field.type){ case "select-one": case "select-multiple": if (field.name.length){ for (j=0, optlen = field.options.length; j < optlen; j++){ option = field.options[j]; if (option.selected){ optvalue = ""; if (option.hasattribute){ optvalue = (option.hasattribute("value") ? option.value : option.text); } else { optvalue = (option.attributes["value"].specified ? option.value : option.text); } parts.push(encodeuricomponent(field.name) + "=" + encodeuricomponent(optvalue)); } } } break; case undefined: //fieldset case "file": //file input case "submit": //submit button case "reset": //reset button case "button": //custom button break; case "radio": //radio button case "checkbox": //checkbox if (!field.checked){ break; } /* falls through */ default: //don't include form fields without names if (field.name.length){ parts.push(encodeuricomponent(field.name) + "=" + encodeuricomponent(field.value)); } } } return parts.join("&"); } osave.onclick = function(){ //创建xhr对象 var xhr; if(window.xmlhttprequest){ xhr = new xmlhttprequest(); }else{ xhr = new activexobject('microsoft.xmlhttp'); } //异步接受响应 xhr.onreadystatechange = function(){ if(xhr.readystate == 4){ if(xhr.status == 200){ //实际操作 var data = json.parse(xhr.responsetext); if(data.success){ document.getelementbyid('createresult').innerhtml = data.msg; }else{ document.getelementbyid('createresult').innerhtml = '出现错误:'+data.msg; } }else{ alert('发生错误:' + xhr.status); } } } //发送请求 xhr.open('post','service.php',true); xhr.setrequestheader("content-type","application/x-www-form-urlencoded"); xhr.send(serialize(document.getelementbyid('postform'))); } </script> </body> </html>
后端页面
<?php //用于过滤不安全的字符 function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } //设置页面内容的html编码格式是utf-8 header("content-type:application/json;charset=utf-8"); //定义一个多维数组,包含员工的信息,每条员工信息为一个数组 $staff = array( array("name"=>"洪七","number"=>"101","sex"=>"男","job"=>'总经理'), array("name"=>"郭靖","number"=>"102","sex"=>"男","job"=>'开发工程师'), array("name"=>"黄蓉","number"=>"103","sex"=>"女","job"=>'产品经理') ); //判断如果是get请求,则进行搜索;如果是post请求,则进行新建 //$_server["request_method"]返回访问页面使用的请求方法 if($_server["request_method"] == "get"){ search(); }else if($_server["request_method"] == "post"){ create(); } //通过员工编号搜索员工 function search(){ //检查是否有员工编号的参数 //isset检测变量是否设置;empty判断值是否为空 if(!isset($_get['number']) || empty($_get['number'])){ echo '{"success":false,"msg":"参数错误"}'; return; } global $staff; $number = test_input($_get['number']); $result = '{"success":false,"msg":"没有找到员工"}'; //遍历$staff多维数组,查找key值为number的员工是否存在。如果存在,则修改返回结果 foreach($staff as $value){ if($value['number'] == $number){ $result = '{"success":true,"msg":"找到员工:员工编号为' .$value["number"] .',员工姓名为' .$value["name"] .',员工性别为' .$value["sex"] .',员工职位为' .$value["job"] .'"}'; break; } } echo $result; } //创建员工 function create(){ //判断信息是否填写完全 if(!isset($_post['name']) || empty($_post['name']) || !isset($_post['number']) || empty($_post['number']) || !isset($_post['sex']) || empty($_post['sex']) || !isset($_post['job']) || empty($_post['job']) ){ echo '{"success":false,"msg":"参数错误,员工信息填写不全"}'; return; } echo '{"success":true,"msg":"员工' .test_input($_post['name']) .'信息保存成功!"}'; } ?>
实例演示
以上所述是小编给大家介绍的ajax 传递json实例代码,希望对大家有所帮助
上一篇: Android 冷启动加沉浸式状态栏