Home>

I am making a request in $.ajax and trying to receive data in the view's js.erb.
The escape processing applied to the data does not return.

I would like to make an associative array that can be used normally in the js.erb views.

$(() =>{
  var fd = new FormData ();
  fd.append ('jsondata', JSON.stringify ({"S": ["1", "2", "3"], "A": ["4", "5"]}))
    $.ajax ({
      type: "POST",
      beforeSend: function (xhr) {
      xhr.setRequestHeader ('X-CSRF-Token',
      $('meta [name = "csrf-token"]'). attr ('content'))
      },
      url: "/ manage/search",
      data: fd,
      dataType: "script",
      processData: false,
      contentType: false,
    });
})
# app/controllers/manage
  def search
    @data = params [: jsondata]
  end
// app/views/manage/search.js.erb
Console.log ("<% = @data%>")

Data displayed on the console when search.js.erb is executed

{&quot;S&quot;: [&quot;1&quot;,&quot;2&quot;,&quot;3&quot;],&quot;A&quot;: [&quot;4&quot;,&quot;5&quot;]}
What I did
    I tried
  1. console.log ("<% = JSON.parse (@data)%>").
  2. I tried as
  3. console.log ("<% = CGI.unescapeHTML (@data)%>").

Neither of the data displayed on the console has changed.
Thanks for your cooperation.

  • Answer # 1

    There is probably a problem with the sender (who uses $.ajax), not the receiver (js.erb).
    I think the reason is thatcontentTypeis not set to'application/json'.

    Please search "jquery ajax json transmission" etc. for details.