You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot下Ajax向控制器发送字符串失败求助

Hey there! Let's work through this issue step by step. You already nailed the part where you get the cell ID on click—awesome progress. Now let's fix the data transfer to your Spring Boot controller. Here's what you need to do:

First, let's recap your existing code to make sure we're on the same page (I'll format it properly):

Your JSP Snippet

<c:forEach items="${rooms2}" var="m" >
  <tr>
    <td style="background-color:OldLace">${m.day }</td>
    <c:choose>
      <c:when test="${m.hour1confirm==false}">
        <td style="background-color:green" id="${m.hour1}" onclick="content(this)" >${m.hour1 }</td>
        <!-- Other <td> elements omitted -->
      </c:when>
    </c:choose>
  </tr>
</c:forEach>

Fixing the JavaScript Function

You've got the elem parameter passed correctly—now we just need to add code to send that ID to your controller. I'll show you two common approaches: native JavaScript (no libraries) and jQuery (since your code snippet hints you might be using it).

Option 1: Native JavaScript with Fetch API

This is modern and doesn't require any external libraries:

function content(elem) {
  // Grab the cell ID you already confirmed works
  const cellId = elem.id;
  console.log("Clicked cell ID:", cellId); // Double-check in browser console

  // Send to Spring Boot controller
  fetch('/api/room-hour', { // Replace with your actual controller endpoint
    method: 'POST', // Use GET if your controller accepts GET requests
    headers: {
      'Content-Type': 'application/json',
      // Critical for Spring Boot's CSRF protection (enabled by default)
      'X-CSRF-TOKEN': document.querySelector('meta[name="_csrf"]').content
    },
    body: JSON.stringify({ id: cellId }) // Package ID as JSON
  })
  .then(response => {
    if (!response.ok) throw new Error(`Request failed: ${response.status}`);
    return response.text(); // Use response.json() if controller returns JSON
  })
  .then(data => {
    console.log("Success! Controller responded:", data);
    // Add post-success logic here (e.g., update cell color)
  })
  .catch(error => {
    console.error("Error sending data:", error);
  });
}

Option 2: jQuery AJAX

If you're already using jQuery in your project, this might feel more familiar:

function content(elem) {
  const cellId = elem.id;
  console.log("Clicked cell ID:", cellId);

  $.ajax({
    url: '/api/room-hour', // Match your controller's path
    type: 'POST',
    contentType: 'application/json',
    data: JSON.stringify({ id: cellId }),
    // Include CSRF token for Spring Boot
    headers: {
      'X-CSRF-TOKEN': $('meta[name="_csrf"]').attr('content')
    },
    success: function(data) {
      console.log("Success!", data);
      // Handle success (e.g., show a message)
    },
    error: function(xhr, status, error) {
      console.error("Request failed:", error);
    }
  });
}

Setting Up Your Spring Boot Controller

You need a controller endpoint to receive the ID. Here's a simple example:

@RestController
@RequestMapping("/api")
public class RoomController {

    // For POST requests with JSON body
    @PostMapping("/room-hour")
    public ResponseEntity<String> receiveRoomHour(@RequestBody RoomRequest request) {
        String receivedId = request.getId();
        // Add your business logic here (e.g., save to database)
        System.out.println("Received cell ID: " + receivedId);
        return ResponseEntity.ok("ID received: " + receivedId);
    }

    // DTO to map the JSON request body
    static class RoomRequest {
        private String id;

        // Getter and setter required for Spring to deserialize
        public String getId() { return id; }
        public void setId(String id) { this.id = id; }
    }

    // If you prefer GET requests (simpler for testing, but less secure for sensitive data)
    @GetMapping("/room-hour")
    public ResponseEntity<String> receiveRoomHourGet(@RequestParam String id) {
        System.out.println("Received cell ID (GET): " + id);
        return ResponseEntity.ok("ID received (GET): " + id);
    }
}

Critical Things to Check

  1. CSRF Token: Add these meta tags to your JSP's <head> to make sure Spring accepts your POST requests:
    <meta name="_csrf" content="${_csrf.token}"/>
    <meta name="_csrf_header" content="${_csrf.headerName}"/>
    
  2. Endpoint Path Match: Make sure the url in your JavaScript exactly matches the @RequestMapping and @PostMapping/@GetMapping paths in your controller.
  3. Browser Dev Tools: Use F12 to open the browser console and Network tab. Check if the request is sending, and look for errors like 404 (wrong endpoint) or 403 (missing CSRF token).

Give this a try, and let me know if you hit any specific errors—I can help troubleshoot further!

内容的提问来源于stack exchange,提问作者Aydin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:08:35