【发布时间】:2012-04-02 17:08:38
【问题描述】:
// main htm page from where aja x call happened
<div id ="vote_count_<%=answer.id %>" >
<%= render :partial => '/votes/count', :locals =>{ :answer => answer} %>//render a partial
<div id="wait" style=" float:center">// for loading image
</div>
</div>
// partial page :- count
<div class ="look6">
<%= image_tag("thumbs_up.jpg", :alt => "like",:value => answer.id,:id => 'like',:class => 'vote')%>// image tag for like reload during ajax call
(<%= Vote.count(answer.id,'like')%>)// no of like vote
| <%= image_tag("thumbs_down.jpg", :alt => "unlike",:value => answer.id,:id =>'unlike',:class => 'vote',:onclick=>"return vote()") %>// image tag for unlike reload during ajax call
(<%= Vote.count(answer.id,'unlike')%>)// no of unlike vote
</div>
// ajax function :-
<script type="text/javascript" >
function showLoadingImage()
{
$('#wait').append('<div id="loading-image"><%= image_tag("ajax-loader.gif", :alt=>"Loading..." )%></div>');// for ajax loading
}
in first page:
//.vote is a claas name
$(".vote").click(function(){
alert("hi");
var answer_id =$(this).attr("value");// for ans id
alert(answer_id);
showLoadingImage();// call loading image function
var result = $(this).attr("id");// whether like or unlike
$.ajax({
cache: false,
//path for controller
url: '/create_vote/'+answer_id,
data: "result="+result,// data for ajax call
complete: function(){
$('#loading-image').remove();// remove loading image
}
});
cache: false;
return false;
});
</script>
//ontroller:
def create_vote
@vote = Vote.new // create new vot
@vote.user_id = current_user.id// user id
@vote.answer_id = params[:id]// answer id
@vote.result = params[:result] == 'like' ? '1':'0'// like or unlike
answer = Answer.find(params[:id])// answer id find
if @vote.save// save vote
@message = "thanks"// message
else
@message = "sorry"// mesage
end
@vote_count = Vote.count(params[:id], params[:result])// total vote
respond_to do |format|
format.js { render '/votes/create_vote.js.erb', :locals => {:result =>params[:result],:answer =>answer}}// result return back
end
end
///votes/create_vote.js.erb $("#vote_count_").html(" '/votes/count', :locals => {:result => result ,:answer =>answer }) %>")// 渲染js部分
//_count 部分 "like",:value => answer.id,:id => 'like',:class=> 'vote')%> () | "unlike",:value => answer.id,:id =>'unlike',:class=> 'vote',:onclick=>"return vote ()") %> ()
【问题讨论】:
标签: ajax