1
我有一個rails 5應用程序,我只是試圖實現一個像按鈕功能。在我的情況下,我在做upvotes。當登錄用戶點擊按鈕時,它應該增加1.我爲用戶和管理員使用設計。Ajax請求與Rails 5應用程序獲取錯誤401(未授權)
我show.html.erb
<% if member_signed_in? %>
<div class"movie-votes">
<medium id="votes"><%= @movie.votes %> members like this film</medium>
<button id="upvote" type="submit">I Like this Film</button>
</div>
我的Ajax請求
"use strict";
console.log("loaded");
$(document).ready(function(){
var member = $("member");
var password = $("password");
$("#upvote").click(function() {
console.log("clicked");
var id = $(this).data("id");
$.ajax({
beforeSend: function(xhr) { xhr.setRequestHeader("Authorization", "Basic " + btoa(member + ":" + password)); },
url: "/movies/votes",
type: "POST",
data: {
member: "[email protected]",
password: "password",
id: id,
votes: true
},
success: function() {
var vote_counter = $("#votes");
// console.log(vote_counter);
var current_vote = parseInt($("#votes").html());
vote_counter.html(current_vote + 1);
alert(vote_counter);
}
})
})
})
MoviesController
before_action :set_movies, only: [:show, :edit, :destroy, :update, :votes]
def votes
@movie.update(votes: @movie.votes + 1)
end
private
def set_movies
@movie = Movie.find(params[:id])
end
的錯誤,當我打開了我越來越合作本地主機上的nsole。
loaded
clicked
jquery.self-660adc5….js?body=1:10246 POST http://localhost:3000/movies/votes 401 (Unauthorized)
發生這種情況後,我點擊「我喜歡這部電影」按鈕。 Sidenote,我現在禁用了turbolinks,因爲這一直是過去的問題。 如果需要,這裏是我的GitHub
你研究過類似的問題嗎? – Nithin
發佈'投票'行動的整個代碼將比僅僅幾行有更多的幫助。這是添加投票功能的非常不安全的方式。你也應該檢查一下,這個用戶是否已經投了票。 – Abhinay
投票動作渲染的反應是什麼? –