简体   繁体   English

Ruby on Rails->动态创建div

[英]Ruby on Rails -> Create div dynamically

I work on a task manager app, and I want to create html div 'cards' (with title, duration etc...), with all the datas I got on a database in rails. 我在一个任务管理器应用程序上工作,我想创建html div'cards'(带有标题,持续时间等...),并将我在数据库中获得的所有数据都存储在rails中。

I guess that I have to use javascript functions, but I can't get a way to do it. 我猜想我必须使用javascript函数,但是我没有办法做到这一点。 I saw a lot of things on google, but I can't find exactly javascript calls from a rails controller (because I only catch all datas in the controller). 我在Google上看到了很多东西,但是我无法从Rails控制器中找到确切的javascript调用(因为我只捕获了控制器中的所有数据)。

Here is my controller : 这是我的控制器:

def new
  # Retrieve all tasks in the project
  @taskModel = Task.new()
  @projectTasks = @taskModel.getProjectTasks()
  # Add tasks on html
  (0..@projectTasks.length).each do |i|
    respond_to do |format|
      format.js { render :js => "window.createTask();" } # I need to pass parameters in the createTask function
    end
  end
end

and my js file : 和我的js文件:

window.createTask = (title, content, duration) ->
  card = document.createElement('div');
  document.getElementsByClassName('content')[0].appendChild(card);

With my code, I get this error : ActionController::UnknownFormat 用我的代码,我收到此错误: ActionController::UnknownFormat

ActionController::UnknownFormat indicated that your ajax request is interpreted as a request with the wrong format. ActionController::UnknownFormat表示您的Ajax请求被解释为格式错误的请求。 To answer this part better you'd have to post the javascript with the ajax call. 为了更好地回答这一部分,您必须使用ajax调用发布javascript。

Secondly, you have to rethink the render in this block 其次,您必须重新考虑此块中的render

(0..@projectTasks.length).each do |i|
    respond_to do |format|
      format.js { render :js => "window.createTask();" } # I need to pass parameters in the createTask function
    end
  end

You are calling respond_to multiple times which is just wrong. 您多次调用respond_to ,这是错误的。 Put this loop into a new.js.erb view. 将此循环放入new.js.erb视图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM