如何使用AJAX替换Rails 3中的div?

Aas*_*h P 2 ajax rjs ruby-on-rails-3

我试图用RJS替换DOM中的div.这是我试过的代码,控制器有这个方法:

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
Run Code Online (Sandbox Code Playgroud)

该视图包含:

<div id = "test_id"></div>
<%= link_to "AJAX", "/poc/change", :remote => true %>
Run Code Online (Sandbox Code Playgroud)

现在我想div id="test_id"用部分提到的替换.

我得到的输出是:

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 }
Run Code Online (Sandbox Code Playgroud)

这在浏览器中可见.任何人都可以解释我哪里错了吗?预期的输出是div应该替换为更换的任何东西.

shi*_*ara 6

我建议你不要再使用RJS了.更好的是生成一个JS视图,你想要你的javascript做.

例如,如果您使用jQuery,您可以添加一个文件:

changes.js.erb

你在里面添加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...'}) %>")
Run Code Online (Sandbox Code Playgroud)

现在,如果你调用/proc/change.js,你可以看到生成的JS就像你在页面中做了一些JS一样.