【问题标题】:Data not inserted to database while using custom ajax request without form in rails在rails中使用没有表单的自定义ajax请求时数据未插入数据库
【发布时间】:2018-09-04 02:47:28
【问题描述】:

我正在尝试在不使用表单的情况下发出 ajax 发布请求,这是我的观点,

查看

<div class="col-md-12">
    <input value="<%= session[:user_id]%>" id="user_id" hidden>
    <%= link_to "Add New", new_task_list_path, :remote => true, :class =>"btn btn-xs add-list" %>
</div>

Ajax

$(document).on('click','.add', function(){
  user_id = $('#user_id').val();
  var name = $('.new-list').val();
  var current = $(this);
  if(name){
    $.ajax({
      method: 'POST',
      url: action,
      dataType: 'JSON',
      data: { 
        task_list: {
          name: name, 
          user_id: user_id 
        }
      }
    }).success(function(e){
      $(current).parent().parent().parent().before(
        '<div class="col-md-12">'+
          '<a href="#" class="btn btn-xs list ">'+name+'</a>'+
        '</div>'
        );
      $(current).parent().parent().parent().remove();
      $('.add-list').show();
    });
  }else{
    alert('please add title');
  }
});

控制器

def create
    @task_list = TaskList.new(task_list_params)
end

private

def task_list_params
    params.require(:task_list).permit(:user_id, :name)
end 

这里,点击 Add New 按钮时触发 ajax post 请求,并将参数传递给控制器​​,返回的状态码是 204 成功但没有数据插入到数据库表中。

我正在使用 postgres 作为数据库。 请帮助我找出我做错了什么。

PS:我是 Rails 新手,如果这是愚蠢的问题,请原谅,如果您需要更多详细信息,请随意询问。

【问题讨论】:

  • 您的日志中是否有任何错误?
  • 我没有收到任何错误,并且在调用后执行 ajax 成功,状态码为 204
  • 多么愚蠢的错误,我只是忘记在创建函数中添加@task_list.save。感谢您的宝贵时间。
  • 哈哈我也没有注意到,只是假设它在那里:D
  • 您确定$(current).parent().parent().parent() 存在吗?

标签: javascript jquery ruby-on-rails ajax postgresql


【解决方案1】:

我认为这个问题发生在 CSRF 令牌上。您可以使用以下步骤解决此问题 -

步骤 1. 将 CSRF 令牌作为元标记添加到您的应用程序布局文件中。

# app/views/layouts/application.html.erb
<head>
 ....
 <%- if protect_against_forgery? %>
   <meta name="authenticity-token" id="authenticity-token" content="<%= form_authenticity_token %>" />
 <% end %>
 ....
</head>

步骤 2. 创建一个新的 JS 文件

# app/assets/javascripts/csrf_token.js
$(function(){
 // always pass csrf tokens on ajax calls
 $.ajaxSetup({
    headers: { 'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content') }
  });
});

步骤 3. 将上面的 js 文件添加到 application.js 中,您的应用程序 js 文件看起来像

# app/assets/javascripts/application.js

//= require rails-ujs
//= require jquery
//= require turbolinks
//= require csrf_token.js

现在你的 ajax 代码应该可以工作了,因为在上面的 ajax 代码之前设置了 Rails 真实性令牌。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-03
    • 1970-01-01
    • 2021-01-24
    • 2016-04-05
    • 2014-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多