【问题标题】:Rails.ajax - Rails is not defined - Rails 7Rails.ajax - Rails 未定义 - Rails 7
【发布时间】:2022-11-13 02:29:02
【问题描述】:
我正在尝试按照本教程来实现 sortablejs:
https://www.youtube.com/watch?v=r884jAqAbHY
我想通过向服务器发送 ajax 更新来保持状态。本教程(Rails 6)通过Rails.ajax 执行此操作
在 Rails 7 中,这会导致控制台错误:
Uncaught ReferenceError: Rails is not defined
在 Rails 7 中执行异步请求的“Rails 方式”是什么?
【问题讨论】:
标签:
javascript
ruby-on-rails
stimulusjs
【解决方案1】:
Fetch 工作 - 我不知道它是否是“Rails 方式”。 . .
fetch("URL", {
method: "PATCH",
headers: {
"X-CSRF-Token": document.querySelector("[name='csrf-token']").content,
},
body: data,
});
【解决方案2】:
您可以使用https://github.com/rails/request.js#how-to-use
例如
import { FetchRequest } from '@rails/request.js'
....
async myMethod () {
const request = new FetchRequest('post', 'localhost:3000/my_endpoint', { body: JSON.stringify({ name: 'Request.JS' }) })
const response = await request.perform()
if (response.ok) {
const body = await response.text
// Do whatever do you want with the response body
// You also are able to call `response.html` or `response.json`, be aware that if you call `response.json` and the response contentType isn't `application/json` there will be raised an error.
}
}