How do you send JSON data to rails-ujs Rails.ajax POST call (without using jQuery)?

I have a React client application that needs to talk to the Rails API. I want to use the rails-ujs Rails.ajax method. For example:

Rails.ajax({
  type: "POST", 
  url: "/things",
  data: mydata,
  success: function(repsonse){...},
  error: function(repsonse){...}
})

It looks like I cannot set the dataJSON for the object as follows:

mydata = {
 thing: {
  field1: value1,
  field2: value2,
}}

I need to convert it to a content type application/x-www-form-urlencodedmanually as follows:

mydata = 'thing[field1]=value1&thing[field2]=value2'

This is normal for flat data, but quickly gets complicated for nested data.

jQuery automatically performs the conversion before executing the query.

So I wonder if Rails UJS has some automatic way to do this , but I could not find anything in the documents or code.

+6
3

ajax- , json, .

var fd = new FormData();
fd.append("jsondata", JSON.stringify(mydata));

$.ajax({
  url: ...
  type :"post",
  data: fd
  success:function(){
  }
})

Json . JSON.parse(params["jsondata"])
, .

+2

, , , , . application/x-www-form-urlencoded. . , , JQuery Ajax .

+1

All Articles