Rails javascript数据库查询

Rails javascript database queries

本文关键字:查询 数据库 javascript Rails      更新时间:2023-09-26

我如何从javascript做一个PUT, POST或DELETE调用?

我已经收集了一些数据使用jquery拖放。然后如何将其发送到数据库?我想我可能会用jQuery。Ajax,但不能确切地工作。

欢迎指教。

解决方案:

这是起作用的javascript

$(document).ready(function() {
  $.ajax({
        type: "PUT",
        url:    "/articles/8", // should be mapped in routes.rb
        data: {articles:{name:"New Name"}}
      });
});

但是它没有将第八条的名称更改为新名称。Firebug没有显示错误,但我仍然无法将数据传递给编辑器。

url是使用put url的标准更新,它存在于路由中。

你可以使用jQuery ajax:这是一个非常好的方式来动态处理浏览器请求与服务器端代码。

jQuery('#element_id').on('click change',function(){ // use event as per your need
       $.ajax({
              type: "GET",
              url:    "/edit_comment", // should be mapped in routes.rb
              data: {comment:"new comment"},
              datatype:"html", // check more option
              success: function(data) {
                       // handle response data
                       },
              async:   true
            });    
});

更多详细信息请查看以下链接:

http://api.jquery.com/jQuery.ajax/

http://api.jquery.com/category/ajax/

RAILs代码

:

def edit_comment
@comment = params[:comment]
// store to database
  response_to do |format|
  render :html 'comment.html'
  end
end

routes.rb

map.edit_comment "edit_comment", :controller => 'comment', :action => 'edit_comment'

为PUT和DELETE添加一个额外的参数_method: _method=PUT
Rails用它来模拟PUT和DELETE