问题描述
我有一个需要与Rails API对话的React客户端应用程序.我想使用 rails-ujs 方法Rails.阿贾克斯例如:
I have a React client app that needs to talk to a Rails API. I want to use the rails-ujs method Rails.ajax. For example:
Rails.ajax({
type: "POST",
url: "/things",
data: mydata,
success: function(response) {...},
error: function(response) {...}
})
似乎无法将 data
设置为这样的JSON对象:
It looks like I can't set data
to a JSON object like this:
mydata = {
thing: {
field1: value1,
field2: value2,
}}
我需要像这样手动将其转换为 application/x-www-form-urlencoded
内容类型:
I need to convert it to a application/x-www-form-urlencoded
content type manually like this:
mydata = 'thing[field1]=value1&thing[field2]=value2'
这对于平面数据来说可以,但是对于嵌套数据来说会很快变得复杂.
This is ok for flat data but gets complicated quickly for nested data.
jQuery在发出请求之前会自动进行转换.
jQuery does the conversion automatically before making a request.
所以我想知道 Rails UJS是否具有某种自动执行方法,但是我在文档或代码中找不到任何内容.
So I'm wondering if Rails UJS has some automatic way of doing it, but I couldn't find anything in the docs or code.
推荐答案
使用启用UJS ,必须将数据格式化为字符串形式的参数.不幸的是,目前无法提供JSON,至少目前不提供Rails 6.0.2(不理想).
When using Rails UJS, data must be formatted as string form parameters. Unfortunately, it's not possible to provide JSON, at least not currently with Rails 6.0.2 (not ideal).
使用 URLSearchParams
来将JSON转换为URL参数:
Use URLSearchParams
to convert JSON to URL paramaters:
myData = {
thing: {
field1: value1,
field2: value2,
}}
Rails.ajax({
type: "POST",
url: "/things",
data: new URLSearchParams(myData).toString()
})
这篇关于如何在rails-ujs Rails.ajax POST调用中发送JSON数据(不使用jQuery)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!