2015-12-20 78 views
-1

我想就我的web应用程序中的喜欢/不喜欢的能力,但我在这里得到错误的错误:用2%的点击 2)请求掌握AJAX请求

1)喜欢/不喜欢的增量发送后,它会更新like/dislike变量,但我必须重新加载页面以查看新的更新数据。

我在做什么错?

这里是我的代码:

我的观点:

#app/views/dashboard/view.html.erb 
<td><span class="glyphicon glyphicon-thumbs-up likeAction"><%= p.like %> </td> 
<td><span class="glyphicon glyphicon-thumbs-down dislikeAction"><%= p.dislike %> </td> 

我的控制器:

#app/controllers/dashboard_controller.rb 
    def like 
    @post=Post.find(params[:id]) 
    @post.increment!(:like) 
    end 

    def dislike 
    @post=Post.find(params[:id]) 
    @post.increment!(:dislike) 
    end 

我的JS文件:

jQuery(function($) { 
    $(".likeAction").click(function(){ 
    var current_post_tr = $(this).parents('tr')[0]; 
    $.ajax({ 
     url: 'http://localhost:3000/dashboard/' + $(current_post_tr).attr('data-post_id') +'/like', 
     type: 'PUT', 
     success: function(){ 
      $("#likeAction").hide().fadeIn(); 
     } 
    }); 
    }); 

    $(".dislikeAction").click(function(){ 
    var current_post_tr = $(this).parents('tr')[0]; 
    $.ajax({ 
     url: 'http://localhost:3000/dashboard/' + $(current_post_tr).attr('data-post_id') +'/dislike', 
     type: 'PUT', 
     success: function(){ 
      $(".dislikeAction").hide().fadeOut(); 
     } 
    }); 
    }); 
}); 

所以,当您的要求成功运行它不会隐藏,然后在不褪色

+0

你的'url'选项应该是一个相对的,而不是绝对的,而不是''http:// localhost:3000/dashboard /'+ ....'' ',还发布了一条错误消息,从代码中不清楚。 –

+0

当我使用相对网址时,我变成了我的路由,如:/ dashboard/29/11/like - 其中29是用户的ID,11是帖子的ID,但我只需要帖子的ID来获取它从参数,所以我试着如你所说,bu没有成为一个正确的网址。我的错误讯息? Chrome控制台表示它是一个外部错误(500),但它更新了post.like或post.dislike的值,只是不会立即显示它 – Handkock

+0

不是Chrome控制台,在rails日志文件中涉及到轨道服务器。 –

回答

0

Relaod页面(location.reload();):

jQuery(function($) { 
    $(".likeAction").click(function(){ 
    var current_post_tr = $(this).parents('tr')[0]; 
    $.ajax({ 
     url: 'http://localhost:3000/dashboard/' + $(current_post_tr).attr('data-post_id') +'/like', 
     type: 'PUT', 
     success: function(){ 
      $(".likeAction").hide().fadeIn(); 
      location.reload(); 
     } 
    }); 
    }); 

    $(".dislikeAction").click(function(){ 
    var current_post_tr = $(this).parents('tr')[0]; 
    $.ajax({ 
     url: 'http://localhost:3000/dashboard/' + $(current_post_tr).attr('data-post_id') +'/dislike', 
     type: 'PUT', 
     success: function(){ 
      $(".dislikeAction").hide().fadeOut(); 
      location.reload(); 
     } 
    }); 
    }); 
}); 

此外,通知:.likeAction代替#likeAction在第一个函数中。此外,请注意.dislikeAction而不是dislikeAction