我尝试使用ajax显示数据,并且完美无缺。但是我有问题如何基于多年的数据创建循环?
year | name |
___________________
2011 | John |
2012 | Smith |
2012 | Billy |
2011 | Charles |
2013 | Kitty |
2010 | Micheal |
2011 | jason |
Ajax数据
<a href="#" onclick="show_year();"> Get </a>
function show_year() {
$.ajax({
url : "<?php echo site_url('my_function/get_year')?>" ,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('#year').val(data.year);
$('#name').val(data.name);
},
error: function (jqXHR, errorThrown)
{
alert('Error ajax');
}
});
}
示例结果
2011
John
Charles
Jason
2012
Smith
Billy
2013
Kitty
答案 0 :(得分:0)
<a href="#" onclick="show_year();"> Get </a>
<div id="responseHtml"></div>
<script type="text/javascript">
function show_year() {
$.ajax({
url : "<?php echo site_url('my_function/get_year')?>" ,
type: "GET",
dataType: "JSON",
success: function(data)
{
var sortArr = data.sort(function(x, y){
return x.year - y.year;
});
var cstYear = '';
var ResultHtml = '';
sortArr.foreach(function(row,index){
if(cstYear !== row.year){
cstYear == row.year;
ResultHtml = '<h4>'+row.year+'</h4>';
}
ResultHtml = '<h6 style="margin-left:30px">'+row.name+'</h4>';
});
$("#responseHtml").html(ResultHtml);
},
error: function (jqXHR, errorThrown)
{
alert('Error ajax');
}
});
}
</script>