所以我试图pollServer();
在haml视图中调用一个脚本,但它没有运行。就是这样:
%div{:id => 'ajaxurl', :class => @poll.id}
:javascript
$(document).ready(function(){
pollServer();
});
这是 pollServer 函数:
$(document).ready(function(){
console.log('here i am');
function pollServer(){
console.log('enter pollServer');
setInterval(function(){
console.log('enter setInterval');
var id = $('div#ajaxurl').attr('class');
$.ajax({
// Div class dynamically set to poll.id
type: 'GET',
dataType: 'json',
url: '/polls/' + id,
complete: function(data){
console.log('pollServer complete');
updateSurvey(data);
},
success: function(data){
console.log('pollServer success');
updateSurvey(data);
},
error: function(){
console.log('pollServer error');
}
});
}, 4000);
};
});
这是处理请求的 PollsController 的显示操作:
def show
@poll = Poll.find(params[:id])
# using for showTotalVotes
gon.votes = @poll.questions[0].answers.map{|answer| answer.votes}
# gon.poll_ids = @poll.questions[0].answers.map{|answer| answer.id}
gon.titles = @poll.questions[0].answers.map{|answer| answer.title}
# gon.poll_data = [gon.poll_ids, gon.titles , gon.votes ]
# => gon.answer = @poll.questions[0].answers
# gon.poll_hash = @poll.questions[0].answers.map{|answer| answer = {:id=> answer.id, :title => answer.title, :votes => answer.votes} }
@question = @poll.questions[0]
@answers = @question.answers
gon.answers = @poll.questions[0].answers
respond_to do |format|
format.html { @poll}
format.js {
render json: gon.answers
}
end
奇怪的是,我的服务器日志实际上轮询我的 rails 服务器并显示 sql db 查询正确地检索指定 ajax 路径的数据,但它不会 console.log('hi') 也不会调用 updateSurvey 方法关于ajax成功。任何想法为什么会发生这种情况?
更新
这是 pollServer 函数应该调用的 updateSurvey 函数
function updateSurvey(all_data){
console.log('balls');
var svg = d3.select('svg')
var bars = svg.selectAll('rect')
.data(all_data)
.transition()
.duration(500)
.attr("y", function(d){
return h + (yOffset - yScale(d.votes))
// return h-(d.votes*10);
})
.attr("height", function(d){
barHeight = yScale(d.votes);
return barHeight;
})
}