【问题标题】:Failed to load resource: the server responded with a status of 500 (Internal Server Error) Ajax Rails error加载资源失败:服务器响应状态为 500 (Internal Server Error) Ajax Rails 错误
【发布时间】:2017-06-25 09:50:56
【问题描述】:

我目前只是想在我的 rails 应用程序中添加一些 ajax。当我尝试创建新帖子时出现此错误。我知道帖子已创建,因为当我刷新页面时,帖子最终会出现在帖子列表中。

posts_controller.rb

  def create
    @post = Post.new(post_params)
    respond_to do |format|
      if @post.save
        format.html { redirect_to @post, notice: 'Post was successfully created.' }
        format.json { render :show, status: :created, location: @post }
        format.js
      else
        format.html { render :new }
        format.json { render json: @post.errors, status: :unprocessable_entity }
        format.js
      end
    end
  end

app/views/posts/index.html.erb

<%= form_for(@post, remote: true) do |f| %>
      <div class="modal fade" id="mynewpost" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
              <h4 class="modal-title" id="myModalLabel">Suggested Invite</h4>
            </div>
            <div class="modal-body">
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-default" data-dismiss="modal" id="mynewpost">Close</button>
              <%= submit_tag "Create", class: "btn btn-primary" %>
            </div>
          </div>

app/views/posts/create.js.erb

alert("Post Created!!");

routes.rb

resources :posts

现在我希望在单击提交后我应该看到 poste 创建了!但我没有。我只是收到内部服务器错误。从这里我不知道该怎么做。如果我可以提供任何其他信息,请告诉我。

【问题讨论】:

  • 当您看到该错误时,您需要在 Rails 控制台中查找原因。将该输出添加到问题中会更容易提供帮助
  • @maxple 不幸的是,我在 docker 容器中运行服务器并且没有收到任何日志。所以我在 Chrome 中使用控制台进行调试
  • 很遗憾您无权访问日志!你不能进入容器吗? docker exec .... /bin/bash 然后你检查日志。更好的是,您可以将 Rails 应用程序的日志目录定义为 docker 卷,以便您可以从开发框访问它。看来您需要先修复开发环境,以便在测试代码时可以看到发生了什么。

标签: javascript ruby-on-rails ruby ajax


【解决方案1】:

看起来可能是语法错误

{ render :show, status: :created, location: @post }

从帖子中渲染 json 并在 javascript 中控制逻辑会更简单。

render json: @post

然后在 javascript 中监听表单是否成功

    $("form").on("ajax:complete", (xhr, status) ->
           alert("Post was created!");
    )
    $("form").("ajax:error", (xhr, data, status) ->
      "Handle errors here";
    )

【讨论】:

  • 这个JS逻辑要放到哪里?
  • 为简单起见,你可以把它放在application.js中
  • 我实际上是用脚手架来创建这些控制器动作的,所以我认为没有语法错误。出于某种原因,我的 format.js 没有受到打击。我知道这一点,因为正在保存数据,除了 format.js 中断之外的所有内容
猜你喜欢
  • 1970-01-01
  • 2017-11-14
  • 2016-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-19
  • 2014-12-12
  • 1970-01-01
相关资源
最近更新 更多