如何使用AJAX来代替DIV在Rails 3的?如何使用、来代替、Rails、AJAX

2023-09-10 14:03:48 作者:說愛太烫嘴

我是想取代我在DOM格使用RJS。这里是code我试过了, 该控制器具有这个方法:

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 %>

现在我想替换 DIV ID =为test_id与部分提到的。

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

我得到的输出是:

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应该被替换为任何更换给出。

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.

推荐答案

我劝您不要使用RJS了。更好的是你希望你做的JavaScript生成一个JS视图。

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

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

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

changes.js.erb

changes.js.erb

在里面你加你的Javascript:

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

现在,如果你调用/proc/change.js可以看到JS生成的,如果你做一些JS在你网页等。

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