开发者

Loading non-RJS javascript via ajax in Rails

开发者 https://www.devze.com 2022-12-31 05:36 出处:网络
I\'ve written a rails module that generates some Javascript for a Google map. As the user makes changes on the webpage, I use observe_field to call back to the server to regenerate the map\'s Javascri

I've written a rails module that generates some Javascript for a Google map. As the user makes changes on the webpage, I use observe_field to call back to the server to regenerate the map's Javascript (without updating the whole page). I'm having trouble finding a good way to insert the new Javascript into the page. I've tried

<div id='my_div_1'>div1</div>
<%= 
  update_page_tag do |page|
    page.replace_html 'my_div_1', "<script>alert('hi');</script>"
  end
%>

but it seems that repla开发者_开发技巧ce_html only works for non-script HTML. It chokes when the content includes the closing </script> tag.

Here is a page that I think is the root of the problem: http://www.wwco.com/~wls/blog/2007/04/25/using-script-in-a-javascript-literal/


Here is one thing that I tried that kind-of worked.

I added an observe_field to the page and then used prototype's Ajax.Updater to get the javascript for the map. It works about 95% of the time but I don't trust it to work out the last 5%. After download and execution of the javascript, it calls an global init_map function that was defined in the download.

<% observe_field(:id_of_field_to_watch, 
:function => "
new Ajax.Updater('map_id', '/filter/map',   
{ 
    evalscripts: true,
    onComplete: function() { init_map() }
}); 
")
%>


What I ended up doing, was getting rid of the dynamic javascript and instead setup the map to be driven by a json data structure. So when the markers for the map change, I'm downloading some json through the rails replace_html method and loading them into the map.

0

精彩评论

暂无评论...
验证码 换一张
取 消