原生js怎樣獲取後臺端口數據

全稱: XMLHttpRequeshtml

<!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>
相關文章
相關標籤/搜索