深入理解ajax系列第七篇

來源:互聯網
上載者:User

標籤:nts   存在   logs   name   send   serial   查詢   and   .com   

前面的話

  雖然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-8header("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系列第七篇

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.