ajax实时更新数据(转载自https://blog.csdn.net/kirsten_z/article/details/56840175)

实现功能:
显示试题结果,并实时更新各题各选项选择人数

示例代码:
控制器 SurveyController.php

public function getResult($id){
$oSuvey = Suvey::find($id);
if(!$oSuvey){
return json_encode(array('success'=>false,'msg'=>'该调研不存在'));
}
$oQuestions = Question::where('sid', $id)
->select('id', 'sid', 'name', 'a', 'a_ct','b', 'b_ct','c','c_ct', 'd','d_ct')
->get();
$aSelection=array('a','b','c','d');
return View::make('show-result')
->with(compact('id', 'oQuestions','aSelection'));
}

public function postResult($id){
$oQuestions = Question::where('sid', $id)
->select('id', 'sid', 'name', 'a', 'a_ct','b', 'b_ct','c','c_ct', 'd','d_ct')
->get();
$aSelection = array('a','b','c','d');
return json_encode(
array(
'success'=>tue,
'oQuestions' => $oQuestions->toArray(),
'aSelection' => $aSelection
)
);
}

 


视图文件 show-result.blade.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>试题</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" />
</head>
<body class="blue_wrapper">
<input type="hidden" id="url" value="{{url()}}/survey/result/{{$id}}" />
@foreach($oQuestions as $k=>$question)
<div class="check_box">
<div class="check_pro">{{$k+1}}、{{$question->name}}</div>
@foreach($aSelection as $selection) 
@if($question->$selection)
<div class="check_list">{{strtoupper($selection)}}、{{$question->$selection}}</div>
<div class="progress_box">
<div class="p_tot">
<div class="progress1"></div>
<div class="progress2" id="<?php echo $selection.'_ct'.($k+1);?>" style="width:<?php $rate = $selection.'_ct';echo $question->$rate*1.24.'%';?>"></div>
</div>
<span class="percent" id="<?php echo $selection.'_ct_'.($k+1);?>"><?php $rate = $selection.'_ct';echo $question->$rate;?>人</span>
</div>
@endif 
@endforeach
</div>
</body>
</html>

 



result.js – 实现实时更新数据

//实时更新数据
$(function(){
function showResult(){
$.ajax({
type: "POST",
url:$('#url').val(),
dataType: "json",
async: true,
cache: false,
timeout:'30000',//请求超时时间
success: function(data) {
if(data.success){
var oQuestions = data.oQuestions;
var aSelection = data.aSelection;
var i = 1;
var j = 0;
var len = oQuestions.length; 
var num = aSelection.length;
var obj = '';
for(; i <= len; i++){
for(; j < num; j++){
obj = document.getElementById(aSelection[j]+'_ct'+i);
obj.style.width = oQuestions[i-1][aSelection[j]+'_ct']*1.24+'%';
$('#'+aSelection[j]+'_ct_'+i).html(oQuestions[i-1][aSelection[j]+'_ct']+'人');
}
j = 0;
}
}
}
});
}
//循环操作
setInterval(function(){showResult();}, 30000); 
});

 



效果如图:

 

 

posted @ 2019-08-08 15:04  远方的异特  阅读(417)  评论(0编辑  收藏  举报