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

2023-12-15

我试图使用 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

该视图包含:

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

现在我想更换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 }

这是在浏览器中看到的。有人能解释一下我哪里出了问题吗?预期的输出是 div 应该被替换为给定的替换内容。


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

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

更改.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...'}) %>")

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 AJAX 替换 Rails 3 中的 div? 的相关文章