我正在使用rails 4.我正在尝试使用ajax
创建动态form_tag所以每次单击“Addsymbol”时,它会触发testpage.js.erb并添加一个新的输入字段(通过ajax呈现)
当单击“发送输入”时,它会触发testpage.html.erb,触发查询并返回将在屏幕上显示的结果
testpage.html.erb
<div id="ajaxsearchform">
<%=render 'searchform'%>
</div>
....code that will show @res on the browser, not important to this topic....
testpage.js.erb
$('#ajaxsearchform').html("<%=j(render('searchform'))%>");
_searchform.html.erb
<%= form_tag '/stinfos/testpage',remote:true do %>
<%=submit_tag "Addsymbol",name:"addsymbol" %>
.....code that handle how many input field to show up, not important to this topic....
<%=submit_tag "Send input",name:"getresult" %></td>
<%end%>
控制器是这样的
if(!params[:addsymbol].nil?)
@numofsymbol+=1
end
if(!params[:getresult].nil?)
request.format = :html
end
...code that will do the query and store result in instance variable @res...
respond_to do |format|
format.js {render layout:'application';}
format.html {render layout:'application';}
end
现在addsymbol工作正常,添加新的输入字段而不刷新整个页面
但是,当我点击“发送输入”时,会显示此
Rendered stinfos/_searchform.html.erb (1.5ms)
Stinfo Load (0.2ms) SELECT `stinfos`.* FROM `stinfos` WHERE (symbol='SVA' OR symbol='' OR symbol='')
Testdatum Load (0.1ms) SELECT symbol,stdate,x52wk_high,x52wk_low FROM `testdata` WHERE
(symbol='SVA' OR symbol='' OR symbol='')
Rendered stinfos/_testshowall.html.erb (1.7ms)
Rendered stinfos/testpage.html.erb within layouts/application (10.6ms)
Rendered layouts/_footer.html.erb (0.1ms)
Completed 200 OK in 1109ms (Views: 1094.7ms | ActiveRecord: 5.4ms)
您可以看到stinfos / testpage.html.erb已成功呈现(因为request.format =:html),但浏览器未显示存储在@res
中的查询结果显示查询结果的唯一方法是---删除form_tag中的remote:true选项---同时保持
其他代码完全一样。在这种情况下,控制台说
Rendered stinfos/_searchform.html.erb (1.7ms)
Stinfo Load (0.2ms) SELECT `stinfos`.* FROM `stinfos` WHERE (symbol='SVA' OR symbol='' OR symbol='')
Testdatum Load (0.1ms) SELECT symbol,stdate,x52wk_high,x52wk_low FROM `testdata` WHERE (symbol='SVA' OR symbol='' OR symbol='')
Rendered stinfos/_testshowall.html.erb (1.9ms)
Rendered stinfos/testpage.html.erb within layouts/application (11.7ms)
Rendered layouts/_footer.html.erb (0.1ms)
Completed 200 OK in 1230ms (Views: 1121.6ms | ActiveRecord: 98.8ms)
Started GET "/assets/estimatechanges.css?body=1" for 66.216.227.139 at 2014-11-07 14:10:16 -0600
Started GET "/assets/custom.css?body=1" for 66.216.227.139 at 2014-11-07 14:10:16 -0600
.....
但是,这不会使用ajax函数,所以当点击addsymbol时屏幕会刷新
请注意,当remote:true启用时,“Started GET ...”行未显示
为什么在远程启用时,渲染的行为会有所不同?
是不是因为我错过了request.format =:html?
之外的任何重要代码