[英]Ruby on Rails: Get json from controller in Javascript file
in my controller I've some json: 在我的控制器中,我有一些json:
votes_controller.rb: tickets_controller.rb:
def create
...
vote_status = current_user.user_votes.pluck(:recipient_uid).include?(@user.uid)
render json: vote_status
end
I need to get vote_status
in javascript file 我需要在javascript文件中获取
vote_status
votes.js: tickets.js:
jQuery(function($) {
$(".doWant").click( function () {
var status = vote_status.evalJSON();
var uid = $(this).parents("#dialog")[0];
var username = $(this).parents("#dialog")[0];
if(confirm("Are you sure?")) {
$.ajax({
url: '/votes' + "?uid=" + $(uid).attr("data-user-uid") + "&username=" + $(username).attr("data-user-username"),
type: 'POST',
success: function(data) {
console.log(data)
}
});
};
});
});
But there is an error Uncaught ReferenceError: vote_status is not defined
. 但是存在错误
Uncaught ReferenceError: vote_status is not defined
。 What am I doing wrong? 我究竟做错了什么?
Thanks! 谢谢!
You're not defining this variable: 您没有定义此变量:
var status = vote_status.evalJSON();
You must define that variable. 您必须定义该变量。
It seems likely that you intended for that code to go into the success
function, which returns the data from the ajax call as the first argument in that function: 您似乎希望使该代码进入
success
函数,该函数将从ajax调用返回的数据作为该函数中的第一个参数:
success: function(data) {
console.log(data)
}
The vote_status is returned in success json callback, init the status there 在成功的json回调中返回vote_status ,在那里初始化状态
$.ajax({
url: '/votes' + "?uid=" + $(uid).attr("data-user-uid") + "&username=" + $(username).attr("data-user-username"),
type: 'POST',
success: function(data) {
var status = JSON.parse(data);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.