我正在尝试编写一个小弹出窗口,在我的应用上添加一个新事件,在rails和Ajax上使用ruby。
我已经实现了Ajax并使操作正常工作,但是在responseText中发送的字符串包含的不仅仅是我试图显示的部分。
从服务器端看,由于它显示的输出,它是有意义的:
Started GET "/events/new.html" for 127.0.0.1 at 2018-01-11 21:58:18 +0100
Processing by EventsController#new as HTML
Rendering events/new.html.erb within layouts/application
Rendered shared/_error_messages.html.erb (0.4ms)
Rendered events/new.html.erb within layouts/application (3.9ms)
Rendered layouts/_rails_default.erb (223.3ms)
Rendered layouts/_shim.html.erb (0.3ms)
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
Rendered layouts/_header.html.erb (1.1ms)
Rendered layouts/_footer.html.erb (0.4ms)
Completed 200 OK in 248ms (Views: 244.1ms | ActiveRecord: 0.2ms)
我可以看到我的服务器从我的事件控制器发送new.html但是我得到了一个错误和一些其他渲染的操作。有谁知道为什么会这样?
我在这里添加了我已实施的代码,以防可能有用
my_app.erb
$(".new_event_button").click(function(){
console.log("click on add new event");
// $("body").append("</%= escape_javascript(render 'events/new') %>");
$("body").append("<div class='new_event_window'></div>");
var req = new XMLHttpRequest();
req.open("GET","/events/new.html");
req.send();
req.onreadystatechange = function () {
console.log(req.readyState);
if (req.readyState === 4) {
$(".new_event_window").append(req.responseText);
}
}
});
事件/ new.html.erb
<h1>New Event</h1>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<%= form_for(@event, url: create_event_path) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.label :title %>
<%= f.text_field :title, class: 'form-control' %>
<%= f.submit "Create my account", class: "btn btn-primary" %>
<%= f.button :cancel, label: "Cancel", class: "btn btn-primary" %>
<% end %>
</div>
</div>
最后是我的事件控制器events_controller.erb
class EventsController < ApplicationController
def new
@event = Event.new
end
def create
end
end
答案 0 :(得分:0)
尝试使用其他方式:
在视图中使用链接
<%= link_to "view", work_path(w), remote: true %>
在控制器上使用响应js
respond_to do |format|
format.js
end
在view.js.erb
中$(".new_event_window").html("<%= j(render 'events/new') %>");
$('#myModal').modal('show')
答案 1 :(得分:0)
你试试这个:
class EventsController < ApplicationController
layout false, only: [:new]
def new
@event = Event.new
end
def create
end
end