How to replace the div in Rails 3 using AJAX?

杀马特。学长 韩版系。学妹 提交于 2019-12-01 08:41:33

问题


I was trying to replace my div in DOM using RJS. Here is the code i tried, The controller has this method:

def change
  render :update do |page|
    page.replace(:test_id, :partial => "input",:locals =>{ :type => 'text', :name => 'user[user][contactinfo][city]', :val => "", :size => '244', :placeholder_text => 'Yes it is working...'})
  end
end

The view contains:

<div id = "test_id"></div>
<%= link_to "AJAX", "/poc/change", :remote => true %>

Now I want to replace the div id="test_id" with the partial mentioned.

The output i get is:

try {
Element.replace("test_id", "<input type=\"text\" id=\"user[user][contactinfo][city]\" name=\"user[user][contactinfo][city]\" value=\"\" placeholder=\"Yes it is working...\" style=\"width:244px; height:33px; border:0; color:#646464; background:url(/images/form_textfield_244.png) 0 5px no-repeat; padding:12px 5px 0 5px; margin:0 0 10px 0;\" />\n");
} catch (e) { alert('RJS error:\n\n' + e.toString()); alert('Element.replace(\"test_id\", \"<input type=\\\"text\\\" id=\\\"user[user][contactinfo][city]\\\" name=\\\"user[user][contactinfo][city]\\\" value=\\\"\\\" placeholder=\\\"Yes it is working...\\\" style=\\\"width:244px; height:33px; border:0; color:#646464; background:url(/images/form_textfield_244.png) 0 5px no-repeat; padding:12px 5px 0 5px; margin:0 0 10px 0;\\\" />\\n\");'); throw e }

This is seen in browser. Can anybody explain where I am going wrong? The expected output is the div should get replaced with whatever given for replacement.


回答1:


I advise you do not use RJS anymore. The better is generate a JS view with you want your javascript do.

By example if you use jQuery you can add a file :

changes.js.erb

Inside you add you Javascript :

$('#test_id').html("<%= escape_javascript(render :partial => "input",:locals =>{ :type => 'text', :name => 'user[user][contactinfo][city]', :val => "", :size => '244', :placeholder_text => 'Yes it is working...'}) %>")

Now if you call the /proc/change.js you can see the JS generated like if you do some JS in you page.



来源:https://stackoverflow.com/questions/5391451/how-to-replace-the-div-in-rails-3-using-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!