原生js怎样获取后台端口数据
全称: XMLHttpReques
<!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> <input type="button" value="登录" id="bnt"></p> <div id="box"></div> </body> </html>