js代码:
//获取用户数据 document.addEventListener("DOMContentLoaded", function () { var context=document.getElementById("spanId").textContent; var colonIndex=context.indexOf(":"); username=context.substring(colonIndex+1).trim(); // 发送Ajax请求获取用户数据 fetch("/User/info?username=" + username) .then(response => { console.log(response.status); console.log(response.json()) ; if (!response.ok) { throw new Error('服务器返回错误.'); } // 检查响应的内容类型是否为 JSON const contentType = response.headers.get('content-type'); if (contentType && contentType.includes('application/json')) { return response.json(); } else { throw new Error('服务器返回的不是有效的 JSON 数据'); } }).then(data => { // 将获取的数据填充到页面中 console.log("服务器响应数据",data); function fillUserData(data) { // 填充用户数据到页面中 document.querySelector(".input-field[name='name']").value = data.name; document.querySelector(".input-field[name='age']").value = data.age; document.querySelector(".input-field[name='gender']").value = data.gender; document.querySelector(".input-field[name='birthdate']").value = data.birthdate; document.querySelector(".input-field[name='address']").value = data.address; document.querySelector(".input-field[name='hobbies']").value = data.hobbies; document.querySelector(".input-field[name='education']").value = data.education; document.querySelector(".input-field[name='occupation']").value = data.occupation; document.querySelector(".input-field[name='phone']").value = data.phone; document.querySelector(".input-field[name='email']").value = data.email; } fillUserData(data); }).catch(error => { // 处理异常情况 console.error('异常:', error); });
springmvc代码:
package com.controller;
import com.dao.Users;
import com.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/User")
public class UsersController{
@Autowired
private UsersService userService;
@GetMapping("/info")
public Users getUserByUsername(@RequestParam String username) {
return userService.getUserByUsername(username);
}
}
服务器URL:http://localhost:8003/MT
错误: