1. 程式人生 > 實用技巧 >原生js實現from功能

原生js實現from功能

程式碼

	<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>XMLHttpReques</title>
    <script>
        var xhr = '';
        if (window.XMLHttpRequest) {
            xhr = new window.XMLHttpRequest();
        } else {
            xhr = new ActiveXObject('Microsoft.XMLHttp');
        }
        window.onload = function () {
            document.getElementById("bnt").onclick = function () {
                xhr.open('post','後臺埠路徑',true);

                xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                var username = document.getElementById('username').value;
                var password = document.getElementById('password').value;
                xhr.send( 'memberId='+ username + '&&password=' + password );
                xhr.onreadystatechange = function () {
                    // readyState: 
                    //     0: 請求未初始化
        //                 1: 伺服器連線已建立
        //                 2: 請求已接收
        //                 3: 請求處理中
        //                 4: 請求已完成,且響應已就緒
        //             status:
        //                 200: 'ok'
        //                 404: 未找到頁面或介面
        //                 xhr.responseText: 後端返回的資料
                        if(xhr.readyState == 4 && xhr.status == 200 ) {
                            document.getElementById('box').innerHTML = xhr.responseText;
                            var json = JSON.parse(xhr.responseText);
                            console.log(json);
                        }

                }
            }
        }
    </script>
</head>
<body>
    <p>賬號:<input type="text" id="username"></p>
    <p>密碼:<input type="password" name="" id="password"></p>
    <p>&nbsp;&nbsp;&nbsp;<input type="button" value="登入" id="bnt"></p>
    <div id="box"></div>
</body>
</html>