前面的話(huà)
雖然ajax全稱(chēng)是asynchronous javascript and XML。但目前使用ajax技術(shù)時(shí),傳遞JSON已經(jīng)成為事實(shí)上的標(biāo)準(zhǔn)。因?yàn)橄噍^于XML而言,JSON簡(jiǎn)單且方便。本文將上一篇中的實(shí)例進(jìn)行改寫(xiě),以JSON的方式來(lái)進(jìn)行數(shù)據(jù)傳遞
前端頁(yè)面
<!-- 前端頁(yè)面 --> <!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>員工查詢(xún)</h2> <label>請(qǐng)輸入員工編號(hào):</label> <input type="text" id="keyword"> <button id="search">查詢(xún)</button> <p id="searchResult"></p> <h2>員工創(chuàng)建</h2> <form id="postForm"> <label>請(qǐng)輸入員工姓名:</label> <input type="text" name="name"><br> <label>請(qǐng)輸入員工編號(hào):</label> <input type="text" name="number"><br> <label>請(qǐng)輸入員工性別:</label> <select name="sex"> <option value="男">男</option> <option value="女">女</option> </select><br> <label>請(qǐng)輸入員工職位:</label> <input type="text" name="job"><br> <button id="save" type="button">保存</button> </form> <p id="createResult"></p> <script> /*get*/ //查詢(xún) var oSearch = document.getElementById('search'); //get方式添加數(shù)據(jù) function addURLParam(url,name,value){ url += (url.indexOf("?") == -1 ? "?" : "&"); url +=encodeURIComponent(name) + "=" + encodeURIComponent(value); return url; } oSearch.onclick = function(){ //創(chuàng)建xhr對(duì)象 var xhr; if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }else{ xhr = new ActiveXObject('Microsoft.XMLHTTP'); } //異步接受響應(yīng) xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ if(xhr.status == 200){ //實(shí)際操作 var data = JSON.parse(xhr.responseText); if(data.success){ document.getElementById('searchResult').innerHTML = data.msg; }else{ document.getElementById('searchResult').innerHTML = '出現(xiàn)錯(cuò)誤:' +data.msg; } }else{ alert('發(fā)生錯(cuò)誤:' + xhr.status); } } } //發(fā)送請(qǐng)求 var url = 'service.php'; url = addURLParam(url,'number',document.getElementById('keyword').value); xhr.open('get',url,true); xhr.send(); } /*post*/ //創(chuàng)建 var oSave = document.getElementById('save'); //post方式添加數(shù)據(jù) 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(){ //創(chuàng)建xhr對(duì)象 var xhr; if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }else{ xhr = new ActiveXObject('Microsoft.XMLHTTP'); } //異步接受響應(yīng) xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ if(xhr.status == 200){ //實(shí)際操作 var data = JSON.parse(xhr.responseText); if(data.success){ document.getElementById('createResult').innerHTML = data.msg; }else{ document.getElementById('createResult').innerHTML = '出現(xiàn)錯(cuò)誤:'+data.msg; } }else{ alert('發(fā)生錯(cuò)誤:' + xhr.status); } } } //發(fā)送請(qǐng)求 xhr.open('post','service.php',true); xhr.setRequestHeader("content-type","application/x-www-form-urlencoded"); xhr.send(serialize(document.getElementById('postForm'))); } </script> </body> </html>
后端頁(yè)面
<?php //用于過(guò)濾不安全的字符 function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } //設(shè)置頁(yè)面內(nèi)容的html編碼格式是utf-8 header("Content-Type:application/json;charset=utf-8"); //定義一個(gè)多維數(shù)組,包含員工的信息,每條員工信息為一個(gè)數(shù)組 $staff = array( array("name"=>"洪七","number"=>"101","sex"=>"男","job"=>'總經(jīng)理'), array("name"=>"郭靖","number"=>"102","sex"=>"男","job"=>'開(kāi)發(fā)工程師'), array("name"=>"黃蓉","number"=>"103","sex"=>"女","job"=>'產(chǎn)品經(jīng)理') ); //判斷如果是get請(qǐng)求,則進(jìn)行搜索;如果是POST請(qǐng)求,則進(jìn)行新建 //$_SERVER["REQUEST_METHOD"]返回訪(fǎng)問(wèn)頁(yè)面使用的請(qǐng)求方法 if($_SERVER["REQUEST_METHOD"] == "GET"){ search(); }else if($_SERVER["REQUEST_METHOD"] == "POST"){ create(); } //通過(guò)員工編號(hào)搜索員工 function search(){ //檢查是否有員工編號(hào)的參數(shù) //isset檢測(cè)變量是否設(shè)置;empty判斷值是否為空 if(!isset($_GET['number']) || empty($_GET['number'])){ echo '{"success":false,"msg":"參數(shù)錯(cuò)誤"}'; return; } global $staff; $number = test_input($_GET['number']); $result = '{"success":false,"msg":"沒(méi)有找到員工"}'; //遍歷$staff多維數(shù)組,查找key值為number的員工是否存在。如果存在,則修改返回結(jié)果 foreach($staff as $value){ if($value['number'] == $number){ $result = '{"success":true,"msg":"找到員工:?jiǎn)T工編號(hào)為' .$value["number"] .',員工姓名為' .$value["name"] .',員工性別為' .$value["sex"] .',員工職位為' .$value["job"] .'"}'; break; } } echo $result; } //創(chuàng)建員工 function create(){ //判斷信息是否填寫(xiě)完全 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":"參數(shù)錯(cuò)誤,員工信息填寫(xiě)不全"}'; return; } echo '{"success":true,"msg":"員工' .test_input($_POST['name']) .'信息保存成功!"}'; } ?>
實(shí)例演示
以上所述是小編給大家介紹的Ajax 傳遞JSON實(shí)例代碼,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com