Javascript 将Ajax与Ruby结合使用
我试图回到Ruby,并创建一个简单的投票系统(比如reddit) 我可以让投票生效,但每次页面都会重新加载。我试图实现一个ajax调用来动态更改值,但我能找到的唯一指南是Rails。我只是将Ruby与Sinatra服务器一起使用 html.erbJavascript 将Ajax与Ruby结合使用,javascript,jquery,ruby,ajax,Javascript,Jquery,Ruby,Ajax,我试图回到Ruby,并创建一个简单的投票系统(比如reddit) 我可以让投票生效,但每次页面都会重新加载。我试图实现一个ajax调用来动态更改值,但我能找到的唯一指南是Rails。我只是将Ruby与Sinatra服务器一起使用 html.erb <form action="/votes" method="post"> <input type="hidden" name="post_id" value="<%= post.id %>"> <
<form action="/votes" method="post">
<input type="hidden" name="post_id" value="<%= post.id %>">
<button id="thumb-up"><img src="/images/thumbs-up.gif" /></button>
</form>
<p> <%= post.votes.count %> </p>
<form action="/votes" method="post">
<input type="hidden" name="_method" value="delete">
<input type="hidden" name="post_id" value="<%= post.id %>">
<button id="thumb-down"><img src="/images/thumbs-down.gif" /></button>
</form>
现在我猜这是一件非常简单的事情,我知道remote:true与此有关
目前,我的拇指向上按钮出现了500个错误,但拇指向下按钮没有,它的url:'delete'
代替了post
我能在没有每个按钮的表单的情况下完成这项工作吗?我也做过同样的事情,如果你像这样调用ajax,这很容易
<%= link_to image_tag(likepic), like_post_path(post,status: true), class: 'vote', method: :put, remote: true %>
like_user_路径转到post控制器中的“like”方法并发布状态:true表示“like”
希望它有用,因为它对我有用
模型是
class Like < ActiveRecord::Base
belongs_to :user
belongs_to :post
end
类类似于
我认为错误在这里:
validates :post, uniqueness: { scope: :user }
这里呢
$.ajax({
url: '/votes',
method: 'post',
success: function() {
console.log('vote up');
$(this).html("<%= post.votes.count %>");
}
})
$.ajax({
url:“/投票”,
方法:“post”,
成功:函数(){
console.log('vote up');
$(this.html(“”);
}
})
您的投票需要一个post id,但您不会在ajax请求中发送一个。提示:学习一些ajax入门教程,并尝试找到一个引入语法
的地方。remote:true
是Rails为您提供ajax的便捷工具。西纳特拉没有任何可比性。你基本上都做得很好,有一些小错误(其中一些是概念性的)<代码>500表示您的服务器代码有错误-并且您没有发布Sinatra路由,因此我们无法对其进行任何说明。正如@7stud所说,您的$(this).html应该传递Ajax响应中的内容,而不是预先呈现的内容(或者更糟糕的是,未呈现的内容)。我可以在没有每个按钮的表单的情况下完成这项工作吗?对按钮不需要表单就可以存在于html页面上。点击按钮时,页面上没有表单。但是,您必须能够使用代码来识别单击了哪个按钮,例如检查其id,这样您就可以告诉服务器在ajax请求中要做什么。他没有使用rails,因此无法访问类似于发布路径的。还有remote:true
哦,对不起,我看不出来
class Like < ActiveRecord::Base
belongs_to :user
belongs_to :post
end
validates :post, uniqueness: { scope: :user }
$.ajax({
url: '/votes',
method: 'post',
success: function() {
console.log('vote up');
$(this).html("<%= post.votes.count %>");
}
})