1. 程式人生 > >深入理解ajax系列第七篇

深入理解ajax系列第七篇

gin 開發工程師 tar component fin hasattr mar tex 員工

前面的話

  雖然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系列第七篇