2024/8/1 13:32:45 ![]()
x
我的部分前端代码如下:<script>getUserProfile({"user_id": user_id})/** * 获取用户资料 * @returns {Promise} 包含用户资料的 Promise 对象 */function getUserProfile(profile) { apiResults = $.ajax({ url: `${API_BASE_URL}/profile.php`, method: 'GET', data: JSON.stringify(profile) }); return apiResults;}
后端API代码如下:if ($_SERVER['REQUEST_METHOD'] == 'GET') { $user_id = getCurrentUserId(); if ($user_id) { // 获取当前登录用户的信息 $query = "SELECT username, email, role FROM users WHERE user_id = :user_id"; $stmt = $db->prepare($query); $stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT); $stmt->execute(); $user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user) { echo json_encode($user); } else { http_response_code(404); echo json_encode(array("message" => "User not found.")); } } else { http_response_code(401); echo json_encode(array("message" => "Unauthorized.")); }}</script>请根据我前端的请求方式修改我的后端代码。2024/8/1 13:32:45 
x
要根据你前端传递的 `user_id` 参数来处理用户资料请求,你需要修改你的后端代码以支持从 GET 请求中解析传递的参数。以下是修改后的后端代码:
### 修改后的后端代码 (profile.php)
```phprequire_once 'init.php';
if ($_SERVER['REQUEST_METHOD'] == 'GET') { // 获取 GET 请求中的 user_id 参数 if (isset($_GET['user_id'])) { $user_id = $_GET['user_id']; // 获取当前用户信息 $query = "SELECT username, email, role FROM users WHERE id = :user_id"; $stmt = $db->prepare($query); $stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT); $stmt->execute(); $user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user) { echo json_encode($user); } else { http_response_code(404); echo json_encode(array("message" => "User not found.")); } } else { http_response_code(400); echo json_encode(array("message" => "User ID is missing.")); }} elseif ($_SERVER['REQUEST_METHOD'] == 'PUT') { // 获取当前登录用户的 ID $user_id = getCurrentUserId(); if ($user_id) { $data = json_decode(file_get_contents("php://input")); $query = "UPDATE users SET username = :username, email = :email WHERE id = :user_id"; $stmt = $db->prepare($query); $stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT); $stmt->bindParam(':username', $data->username); $stmt->bindParam(':email', $data->email);
if ($stmt->execute()) { echo json_encode(array("message" => "Profile was updated.")); } else { http_response_code(503); echo json_encode(array("message" => "Unable to update profile.")); } } else { http_response_code(401); echo json_encode(array("message" => "Unauthorized.")); }} else { http_response_code(405); // Method Not Allowed echo json_encode(array("message" => "Method not allowed."));}```
### 修改后的前端代码
根据前端请求格式的不同,调整你的 AJAX 调用,确保数据通过 URL 参数传递。
```javascript<script>/** * 获取用户资料 * @param {Object} profile 包含用户 ID 的对象 * @returns {Promise} 包含用户资料的 Promise 对象 */function getUserProfile(profile) { return $.ajax({ url: `${API_BASE_URL}/profile.php`, method: 'GET', data: profile // 传递参数 });}```
### 使用示例
```javascript$(document).ready(function () { const user_id = 1; // 假设用户 ID 为 1
// 获取用户资料 getUserProfile({ user_id: user_id }) .then(function (profile) { $('#username').val(profile.username); $('#email').val(profile.email); $('#role').val(profile.role); }) .catch(function () { alert('Failed to load profile. Please try again.'); });});</script>```
通过这些更改,你可以确保前端和后端之间的通信正常工作,并且能够基于传递的 `user_id` 获取相应的用户资料。
2024/8/1 13:32:45 ![]()
x
上面的代码并未成功,请检查我的login.html中的前端代码如下,是否有问题。<script>loginUser({ username: username, password: password }).then(function(response) { response = JSON.parse(response); // console.log(response.role); // 打印响应数据 // 根据用户角色重定向到不同的主页 sessionStorage.setItem('user_id', response.user_id); if (response.role === 'admin') { window.location.href = 'admin_dashboard.html'; } else if (response.role === 'teacher') { window.location.href = 'teacher_dashboard.html'; } else { window.location.href = 'student_dashboard.html'; } })</script>2024/8/1 13:32:45 
x
在调试你的代码之前,我们需要确保以下几点:
1. **后端`login.php`的响应中包含`user_id`**。2. **前端能够正确地从响应中提取`user_id`并存储到`sessionStorage`**。3. **前端在获取用户资料时能够正确地从`sessionStorage`中读取`user_id`并发送到后端**。
### 1. 确保后端`login.php`的响应中包含`user_id`
首先,确保你的`login.php`在用户成功登录后返回了`user_id`。以下是一个示例:
```phprequire_once 'init.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') { $data = json_decode(file_get_contents("php://input")); $username = $data->username; $password = $data->password;
// 查询用户信息 $query = "SELECT id, username, password, role FROM users WHERE username = :username"; $stmt = $db->prepare($query); $stmt->bindParam(':username', $username); $stmt->execute(); $user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user) { // 验证密码(假设数据库中存储的是哈希密码) if (password_verify($password, $user['password'])) { // 设置会话变量 $_SESSION['user_id'] = $user['id'];
// 返回用户信息,包括role和user_id echo json_encode(array( "message" => "Login successful.", "role" => $user['role'], "user_id" => $user['id'] )); } else { http_response_code(401); // Unauthorized echo json_encode(array("message" => "Invalid password.")); } } else { http_response_code(404); // Not Found echo json_encode(array("message" => "User not found.")); }} else { http_response_code(405); // Method Not Allowed echo json_encode(array("message" => "Method not allowed."));}```
### 2. 前端正确保存`user_id`到`sessionStorage`
确保你的前端代码正确地保存了`user_id`到`sessionStorage`中。以下是你的`login.html`中的JavaScript代码:
```javascript<script src="script.js"></script><script> $(document).ready(function() { $('#loginForm').on('submit', function(event) { event.preventDefault(); const username = $('#username').val(); const password = $('#password').val();
// 调用封装的 API 方法进行用户登录 loginUser({ username: username, password: password }).then(function(response) { response = JSON.parse(response); // 将 user_id 保存到 sessionStorage sessionStorage.setItem('user_id', response.user_id); // 根据用户角色重定向到不同的主页 if (response.role === 'admin') { window.location.href = 'admin_dashboard.html'; } else if (response.role === 'teacher') { window.location.href = 'teacher_dashboard.html'; } else { window.location.href = 'student_dashboard.html'; } }).catch(function() { alert('Login failed. Please check your username and password.'); }); }); });</script>```
### 3. 获取用户资料时从`sessionStorage`中取得`user_id`
修改你的`getUserProfile`函数,以便从`sessionStorage`中获取`user_id`并发送到后端:
```javascript<script>/** * 获取用户资料 * @returns {Promise} 包含用户资料的 Promise 对象 */function getUserProfile() { const user_id = sessionStorage.getItem('user_id'); return $.ajax({ url: `${API_BASE_URL}/profile.php`, method: 'GET', data: { user_id: user_id } // 传递 user_id 作为参数 });}```
### 验证修改后的代码
确保你的其他前端代码调用了新的`getUserProfile`函数。例如:
```javascript$(document).ready(function() { // 加载用户信息 function loadProfile() { getUserProfile() .then(function(profile) { $('#username').val(profile.username); $('#email').val(profile.email); $('#role').val(profile.role); }) .catch(function() { alert('Failed to load profile. Please try again.'); }); }
// 在页面加载时调用 loadProfile();});</script>```
通过这些步骤,你应能成功实现登录后保存`user_id`到`sessionStorage`,并在后续请求中正确传递`user_id`以获取用户资料。