如何在控制器的动作中显示模态窗口? [英] how to show modal window in controller's action?
问题描述
所以我有控制器PagesController与动作索引和full_search。动作索引是主页。在主页上,我有搜索按钮和text_field。如果用户在text_field中键入sometiong并单击搜索按钮,则他/她将转到操作full_search。在这个动作中,我尝试通过用户的查询找到一些东西。如果我找不到任何东西,我应该只显示一个模式窗口,其中无结果,否则重定向到另一个页面
So I've got controller PagesController with actions index and full_search. Action index is for home page. On home page I've got the button 'search' and text_field. If user types sometiong in text_field and clicks on button 'search' he/she goes to action full_search. In this action I try to find something by user's query. if I don't find anything I should just show a modal window with 'no results' otherwise redirect to another page
def full_search
...do search...
if search_result.empty?
show modal window with text 'no results'
else
redirect to another page
end
end
如何显示模态窗口(如js中的函数警报)?我想我必须使用javascript..but ????
How can I show modal window(like function alert in js)? I think I have to use javascript..but where???
如果search_result是空的我不需要渲染任何视图...我只需要留下在同一页面并显示模态窗口
if search_result is empty I don't need to render any view...I just need to stay at the same page and show modal window
推荐答案
第1步。
在你的渲染视图中,有一个id为my_modal_content的div,其中将插入模态的内容并显示模态。
In your rendered view, have a div with id "my_modal_content" where will insert the modal's content and show the modal.
第2步。
渲染一个js.erb文件,该文件会将模态附加到我们的页面
Render a js.erb file which will append the modal to our page
#your rails controller method
def my_method
if something == true
respond_to do |format|
format.js { render :partial => 'somewhere/somefile.js.erb' }
#I'm assuming its js request
end
else
redirect to another page
end
end
第4步。
像这样写你的js.erb文件,它附加模态然后显示它。
Write your js.erb file like this, which appends modal and then shows it.
#_somefile.js.erb file
$("#my_modal_content").html("<%= escape_javascript(render 'somewhere/my_modal') %>");
$("#myModal").modal('show');
第3步。
模态部分文件 _my_modal.html.erb
置于 views / somewhere /
准备你的模态内容。
Modal partial file _my_modal.html.erb
placed within views/somewhere/
with you modal content ready.
<div class="modal fade" tabindex="-1" id="myModal" role="dialog">
<div class="modal-dialog">
...<!-- all your content insdie -->
</div>
</div>
更新
Update
如果你想要显示警报,它非常直接。你只需渲染js
If you want to show an alert, its pretty straight forward. You just render js
if search_result.empty?
message = "No result found. Try something else!"
respond_to do |format|
format.js { render js: "alert(#{message});" }
end
else
redirect to another page
end
这篇关于如何在控制器的动作中显示模态窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!