写一段PHP和js交互的代码
时间: 2023-12-01 22:55:16 浏览: 29
以下是一个简单的PHP和JS交互的代码示例:
PHP:
```
<?php
// 获取POST请求中的用户名和密码
$username = $_POST['username'];
$password = $_POST['password'];
// 验证用户名和密码是否正确
if ($username == 'admin' && $password == '123456') {
// 登录成功,返回一个JSON对象
$response = array('status' => 'success', 'message' => '登录成功');
echo json_encode($response);
} else {
// 登录失败,返回一个JSON对象
$response = array('status' => 'fail', 'message' => '用户名或密码错误');
echo json_encode($response);
}
?>
```
JS:
```
// 监听表单的提交事件
document.getElementById('login-form').addEventListener('submit', function(event) {
// 阻止表单的默认提交行为
event.preventDefault();
// 获取用户名和密码
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
// 发送POST请求
var xhr = new XMLHttpRequest();
xhr.open('POST', 'login.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
// 处理服务器返回的JSON对象
var response = JSON.parse(xhr.responseText);
if (response.status == 'success') {
alert(response.message);
// 登录成功后的操作
} else {
alert(response.message);
// 登录失败后的操作
}
}
};
xhr.send('username=' + encodeURIComponent(username) + '&password=' + encodeURIComponent(password));
});
```
在这个示例中,JS监听了表单的提交事件,并阻止了表单的默认提交行为。然后获取表单中的用户名和密码,发送POST请求到PHP服务器。PHP服务器接收到请求后,验证用户名和密码是否正确,然后返回一个JSON对象。JS在接收到服务器返回的JSON对象后,根据返回值进行相应的操作。