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

Play Framework中HTML onclick转Ajax JS函数遇问题求助

Fixing Play Framework Ajax Delete Button Issue in Chrome

Hey there! Let's work through this delete button issue you're having with Play Framework and Chrome. I see a couple of potential culprits here, and we'll fix them step by step.

First, Rule Out CSRF Protection (The Most Common Gotcha)

Play Framework enables CSRF protection by default for non-GET requests like DELETE. If you don't include the CSRF token in your Ajax call, the request will fail silently (or throw a 403 error in the console), which might look like your onclick isn't working.

Fix: Add CSRF Token to Your Request

  1. Add a meta tag for the CSRF token in your main Layout.scala.html template inside the <head> section:
<meta name="csrf-token" content="@helper.CSRF.getToken.value">
  1. We'll include this token in the Ajax request headers in the next step.

Second, Replace Inline onclick with Clean Event Binding

Inline event handlers can cause quote nesting issues (especially if your route URLs ever have special characters) and are harder to maintain. Let's use data attributes to store the URLs, then bind the click event with jQuery.

Update Your show.scala.html Button

Replace your delete button with this—we'll use data attributes to hold the URLs instead of passing them directly in onclick:

<button class="btn btn-danger" 
        data-delete-url="@routes.BooksController.destroy(book.id)" 
        data-redirect-url="@routes.HomeController.index()">
  Delete
</button>

Rewrite Your custom.js File

Update your JavaScript to use event delegation (this works even if the button is added dynamically later) and include the CSRF token:

// Wait for the DOM to be fully loaded before binding events
$(document).ready(function() {
  // Bind click event to all delete buttons
  $('.btn-danger').on('click', function() {
    // Get the URLs from the data attributes
    const deleteUrl = $(this).data('delete-url');
    const redirectUrl = $(this).data('redirect-url');
    // Get the CSRF token from the meta tag
    const csrfToken = $('meta[name="csrf-token"]').attr('content');

    $.ajax({
      url: deleteUrl,
      method: 'DELETE',
      // Include the CSRF token in the request headers
      headers: {
        'X-CSRF-Token': csrfToken
      },
      success: function() {
        // Redirect to the index page on success
        window.location.href = redirectUrl;
      },
      error: function(xhr) {
        // Log the error to the console for debugging
        console.error('Delete request failed:', xhr.responseText);
        window.location.reload();
      }
    });
  });
});

Finally, Double-Check jQuery is Loaded

Make sure you're including jQuery in your layout template before your custom.js file. If jQuery isn't loaded, $ will be undefined, and your Ajax call won't run. Add this before your custom.js script tag:

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<!-- Or use a local copy if you prefer -->
<script src="@routes.Assets.versioned("javascripts/custom.js")"></script>

Why Your Original Code Might Have Failed

  • Quote nesting issues: The inline onclick uses single quotes inside double quotes, which should work in theory, but if your route generated a URL with unexpected special characters (unlikely, but possible), it could break attribute parsing.
  • Missing CSRF token: Play would reject the DELETE request without the token, making it seem like the onclick wasn't firing.
  • Incorrect event binding in commented code: You tried setting the button's id to a function call (id="sendDeleteRequest(...)"), which is invalid—IDs must be plain strings, not executable code.

Give these changes a try, and check the Chrome DevTools Console (F12) for any error messages if something still doesn't work—this will help pinpoint any remaining issues.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:33:25