在rails项目里面什么是SJR-stimulus示例


SJR = Server-generated JavaScript Responses
服务器端生成并返回javascript代码

Server creates or updates a model object. Server generates a JavaScript response that includes the updated HTML template for the model. Client evaluates the JavaScript returned by the server, which then updates the DOM.

stimulus.js: 处理局部js请求。

Turbo: 处理前后端页面无刷新加载。


rails - stimulus.js  前端check_box的点击调用后台controller处理的代码示例。

<div class="block">
  <%= form_with(model: task, class:"text-lg inline-block my-3 w-72") do |form| %>
    <%= form.check_box :completed,
                       data: {
                         id: task.id,
                         action: "tasks#toggle"
                       },
                       class: "mr-2 align-middle bg-gray-50 border-gray-300 focus:ring-3 focus:ring-blue-300 h-5 w-5 rounded checked:bg-green-500" %>
    <%= task.description %>
  <% end %>


When Rails renders this template, it spits out the following HTML.

</div><input data-id="1" data-action="tasks#toggle" class="mr-2 .." type="checkbox" value="1" name="task[completed]" id="task_completed">



import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
    connect() {
        console.log(this.element)
    }

    toggle(e) {
        const id = e.target.dataset.id
        const csrfToken = document.querySelector("[name='csrf-token']").content

        fetch(`/tasks/${id}/toggle`, {
            method: 'POST', // *GET, POST, PUT, DELETE, etc.
            mode: 'cors', // no-cors, *cors, same-origin
            cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
            credentials: 'same-origin', // include, *same-origin, omit
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-Token': csrfToken
            },
            body: JSON.stringify({ completed: e.target.checked }) // body data type must match "Content-Type" header
        })
          .then(response => response.json())
          .then(data => {
             alert(data.message)
           })
    }
}


There are a few points to note in the above method.
  1. The toggle method takes the event as a parameter. We can access the checkbox element from the target property of the event.
  2. We retrieve the task id from the data attribute on the element, which we set earlier. Then we pass the id in the URL.
  3. We are passing the csrfToken in the header. I wrote about the Cross-Site Request Forgery vulnerability and CSRF tokens in my post Understanding Authenticity Tokens in Rails. Check it out if you're interested in learning more.
  4. The body contains whether the checkbox was selected or not, letting the server know if the task is completed or marked incomplete.



https://www.akshaykhot.com/building-to-do-list-using-hotwire-and-stimulus/
阅读量: 1023
发布于:
修改于: