这次给大家带来在实战项目中Ajax应该如何传递JSON,在实战项目中Ajax传递JSON的注意事项有哪些,下面就是实战案例,一起来看一下。
前面的话
虽然ajax全称是asynchronous javascript and XML。但目前使用ajax技术时,传递JSON已经成为事实上的标准。因为相较于XML而言,JSON简单且方便。本文将上一篇中的实例进行改写,以JSON的方式来进行数据传递
前端页面
Document body{font-size: 20px;margin: 0;line-height: 1.5;}select,button,input{font-size: 20px;line-height: 1.5;}员工查询
员工创建
男 女
/*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')));}
登录后复制
后端页面
"洪七","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']) .'信息保存成功!"}';}?>
登录后复制
实例演示
相信看了本文案例你已经掌握了方法,更多精彩请关注【创想鸟】其它相关文章!
推荐阅读:
C与View之间怎么进行数据交流
Ajax直接实现点赞功能步奏详解
以上就是在实战项目中Ajax应该如何传递JSON的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2776309.html