所以我试图在haml视图中调用pollServer();
脚本,但它没有运行。以下是:
%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的处理请求的show动作:
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&# 39;)也没有在ajax成功时调用updateSurvey方法。有什么想法可能会发生这种情况吗?
更新
这里是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;
})
}
答案 0 :(得分:1)
我认为你的服务器正在以不正确的内容类型返回json。 我运行这段代码:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
function pollServer(){
setInterval(function(){
console.log('hi');
$.ajax({
type: 'GET',
dataType: 'json',
url: 'http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true',
success: function(data){
console.log('hi');
updateSurvey(data);
}
});
}, 4000);
};
$(document).ready(function()
pollServer();
});
</script>
得到
hi
ReferenceError: Can't find variable: updateSurve
这可以解释两者 - 为什么没有运行js代码而服务器端的SQL是。