1. 程式人生 > >ajax表單查詢與寫入

ajax表單查詢與寫入

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        *{
            font-size: 30px;
            line-height: 1.8;
        }
    </style>
</head>
<body>
    <h1>員工查詢</h1>
    <label>請輸入員工編號</label>
    <input type="text" id="keyword">
    <button id="search">查詢</button>
    <p id="searchResult"></p>

    <h1>員工建立</h1>
    <label>請輸入員工姓名</label>
    <input type="text" id="staffName"><br>

    <label>請輸入員工編號</label>
    <input type="text" id="staffNumber"><br>

    <label>請輸入員工性別</label>
    <select id="staffSex">
        <option>男</option>
        <option>女</option>
    </select><br>

    <label>請輸入員工編號</label>
    <input type="text" id="staffJob">
    <button id="save">儲存</button>
    <p id="createResult"></p>
    <script>
        document.getElementById('search').onclick=function(){
            var request = new XMLHttpRequest();
            request.open("get","server.php?number="+document.getElementById("keyword").value);
            request.send();
                request.onreadystatechange = function() {
               if(request.readyState===4) {
                if(request.status===200){
                  document.getElementById("searchResult").innerHTML = request.responseText;
                }else {
                    alert("發生錯誤:"+request.statue);
                }
               }
            }
        }

document.getElementById("save").onclick = function() { 
    var request = new XMLHttpRequest();
    request.open("POST", "server.php");
    var data = "name=" + document.getElementById("staffName").value 
                      + "&number=" + document.getElementById("staffNumber").value 
                      + "&sex=" + document.getElementById("staffSex").value 
                      + "&job=" + document.getElementById("staffJob").value;
    request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    request.send(data);
    request.onreadystatechange = function() {
        if (request.readyState===4) {
            if (request.status===200) { 
                document.getElementById("createResult").innerHTML = request.responseText;
            } else {
                alert("發生錯誤:" + request.status);
            }
        } 
    }
}
    </script>
</body>
</html>

json

        request.onreadystatechange = function() {
        if (request.readyState===4) {
            if (request.status===200) { 
                var data = JSON.parse(request.responseText);
                if (data.success) { 
                    document.getElementById("searchResult").innerHTML = data.msg;
                } else {
                    document.getElementById("searchResult").innerHTML = "出現錯誤:" + data.msg;
                }
            } else {
                alert("發生錯誤:" + request.status);
            }
        } 
    }