Ajax发送POST请求

要点:

        1.基本步骤跟上一个的get方式请求,不过post请求,请求头是包含了有用的信息的,所以需要在请求头上指定Content-Type解析请求体格式,get方式请求体信息是放在query中的,不太安全。

        2.在请求体中不要有空格,实际文字和模板字符串之间,不能因为js代码习惯,破坏了请求体规定的格式,造成错误。

php代码:

<?php 
  
  if(empty($_POST['username']) || empty($_POST['password'])){
  	exit('请输入完整信息');
  }

  $username = $_POST['username'];
  $password = $_POST['password'];

  if($username === 'cyj' && $password === '123456'){
  	exit('登录成功');
  }

  exit('输入信息有误');

html代码:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
    <div id="loading"></div>
	<table>
		<tr>
			<td>用户名</td>
			<td><input type="text" id="username"></td>
		</tr>
		<tr>
			<td>密码</td>
			<td><input type="password" id="password"></td>
		</tr>
		<tr>
			<td></td>
			<td><button id="btn">登录</button></td>
		</tr>
	</table>

	<script type="text/javascript">
		var btn = document.getElementById('btn')
		var textUsername = document.getElementById('username')
		var textPassword = document.getElementById('password')

		btn.onclick = function(){
			var username = textUsername.value
			var password = textPassword.value

			var xhr = new XMLHttpRequest()
			xhr.open('POST','login.php')
			// 以POST请求方式请求login.php
            
            xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
            // 通过post方式发送urlencoded格式请求体,必须设置相应的请求头

			xhr.send(`username=${username}&password=${password}`)
			// es6新语法,模板字符串,通过esc键下面一个键的反引号,括起来的。注意这里面有固定格式,千万别有空格

			xhr.onreadystatechange = function(){
				if(this.readyState == 4){
                   alert(this.responseText)
				} 
			}
		}
	</script>
</body>
</html>

效果:

猜你喜欢

转载自blog.csdn.net/qq_42036616/article/details/84973031