2008年6月23日 星期一

like widget, use javascript take some data from host


[In someone's blog]
Here need send some request to our host
<script src='http://your_host/controller_name/action_name?q=2357,2388,2324&id=anything'></script>

that will become
params[:q] = '2357,2388,2324'
params[:id]= 'anything'

[Our controller ]
We have to return javascript to do something like insert some content

def action_name
@element_id = params[:id]

targets_id = [params[:q].split(',')].flatten.slice(0,2).compact
targets = Target.find(:all, :conditions => { :target_id => targets_id})

#@content is some data we want to insert it, and we encode it by function to_json,
#content may have something that javascript may have some problems in handling
#So, we encode all content by to_json to javascript type data
@content = render_to_string(:partial => 'content_partial', :locals => {:targets => targets}).to_json

#we don't need layout
render :layout => false

#we should return javascript, so we change the header
response.headers['Content-Type']='text/javascript'
end

[View]
this javascript will be received by your blog to do something like insert some content
(function(){
var quote_data =<%= @content %>;
document.write('<div id="<%= @element_id%>">'+quote_data+'</div>');
})();

[content_partial]
We use the id to make our css style would be unique
<style>
<% eid = "##{@element_id}" %>
<%=eid%> .scroll {
background-image: url(http://host/public_inside/images/bg_scroll.gif);
background-repeat: no-repeat;
height: 8px;
width: 268px;
*width: 310px;
}
</style>

<div class="scroll" >
<MARQUEE direction="left" loop="true" scrollamount="4" scrolldelay="100" >
<% targets.each do |t| -%>
<a href="<%= back_link_url(:controller => 'target', :action => 'show', :id => t) %>" target="_blank">
</a>
<% end -%>
</MARQUEE>
</div>

[helper]
#We should insert the complete url to link back
def back_link_url(options)
request.protocol + request.host_with_port + url_for(options)
end

沒有留言: