【问题标题】:Stimulus ajax:response not returning the server response data刺激 ajax:response 不返回服务器响应数据
【发布时间】:2022-01-02 20:54:44
【问题描述】:

我正在启动一个新的 Rails 7 应用程序,最近发现我们不能再使用 ujs :( 我发现一个名为 mrujs 的插件可以正常工作,可以将我的表单远程发送到服务器。我也在使用刺激处理页面上的各种javascript函数。

我遇到的问题是我在 ajax:success processes is not iterable 之后的回复:

TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator))

下面是我的 HTML、Rails 和 Stimulus 代码:

HTML

<%= form_with model: Article.new, html: { data: { remote: true, type: "html", "action": "ajax:success->modal-forms#onPostSuccess ajax:error->modal-forms#onPostError" } } do |f| %>
  <%= f.label :title, "Article Title" %>
  <%= f.text_field :title, class: "form-control" %>
  <%= f.submit "Save Article", class: "btn btn-primary" %>
<% end %>

Ruby / Rails

def create
  @article = Article.create(article_params)
  if @article.errors.any?
    render partial: 'error', article: @article, status: :bad_request
  else
    render @article
  end
end

这将返回一个基本的 html 页面,该页面将被插入到页面中的另一个位置。

<li><%= @article.title %></li>

刺激作用

onPostSuccess(event) {
  event.preventDefault()
  const [data, status, xhr] = event.detail
  // This is where I get the issue of 'Not Iterable'
}

event.detail 给了我不可迭代的错误。有谁知道我怎样才能让我从 rails 得到的回复被格式化,这样[data, status, xhr] 部分才能真正起作用?

如果需要 hotwire 或 turbo 的话,一个例子会非常有帮助:)

谢谢 埃里克

【问题讨论】:

    标签: ajax ujs stimulusjs hotwire-rails ruby-on-rails-7


    【解决方案1】:

    这可能不是正确的方法,但确实有效:

    html

    <div data-container="remote">
    <%= form_with model: Person.new, html: { data: { "action": "submit->remote#submit" } } do |f| %>
        <%= f.text_field :first_name %>
        <%= f.submit :submit %>
      <% end %>
    </div>
    

    轨道控制器

    def create
        @person = Person.new(person_params)
        if @person.save
          render json: @person
        else
          render partial: 'people/person', locals: { person: @person },  status: :unprocessable_entity
        end
      end
    

    远程刺激控制器

    submit(event) {
        event.preventDefault()
    
        fetch(event.target.action, {
          method: 'POST',
          body: new FormData(event.target),
        }).then(response => {
          console.log(response);
          if(response.ok) {
            return response.json()
          }
    
          return Promise.reject(response)
        }).then(data => {
          console.log(data)
        }).catch( error => {
          console.warn(error)
        });
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多