一、效果展示
有时候需要在页面请求后台获取数据:这里就用到了ajax去后台获取数据:
数据库的数据是这样的:
mysql> select * from ocenter_travel_class_info where pid = 0;
+-----+-----+----------------+------------+
| id | pid | class_name | basic_code |
+-----+-----+----------------+------------+
| 1 | 0 | 地文景观 | A |
| 2 | 0 | 水域风光 | B |
| 3 | 0 | 生物景观 | C |
| 4 | 0 | 天象与气候景观 | D |
| 5 | 0 | 遗址遗迹 | E |
| 6 | 0 | 建筑与设施 | F |
| 7 | 0 | 旅游商品 | G |
| 8 | 0 | 人文活动 | H |
| 198 | 0 | 自然景观 | I |
+-----+-----+----------------+------------+
9 rows in set (0.00 sec)
二、步骤
1、首先在HTML页面中使用$(function(){});
在页面加载完成后用ajax去后台获取数据:
<!-- ......省略部分代码......-->
<script type="text/javascript">$(function(){$.ajax({type:'post',url:"{:U('Tour/main_data')}",dataType:"json",data:{pid:0},success:function(data){// console.log(data);$("#main_id").empty();$("#main_id").append("<option value=''>请选择主类</option>");for(var i=0;i<data.length;i++){$("#main_id").append('<option value='+data[i].id+'>'+data[i].class_name+'</option>');}}});
</script>
<!-- ......省略部分代码......-->
<label class="col-sm-2 control-label"><font color="red">* </font>主类 名称 </label>
<div class="col-sm-4"><select name="main_id" id="main_id" class="text input-large form-control"><option value="">请选择主类</option></select>
</div>
<!-- ......省略部分代码......-->
2、后台控制器的方法中去数据库获取数据:
//获取后台主类数据
public function main_data(){$class_id = I('pid');if($class_id == 0){$Travel = M('travel_class_info');$travel_list = $Travel->where('pid=0')->select();$this->ajaxReturn($travel_list);}
}
3、打印方法中的json数据:
[{"id": "1","pid": "0","class_name": "地文景观","basic_code": "A"
}, {"id": "2","pid": "0","class_name": "水域风光","basic_code": "B"
}, {"id": "3","pid": "0","class_name": "生物景观","basic_code": "C"
}, {"id": "4","pid": "0","class_name": "天象与气候景观","basic_code": "D"
}, {"id": "5","pid": "0","class_name": "遗址遗迹","basic_code": "E"
}, {"id": "6","pid": "0","class_name": "建筑与设施","basic_code": "F"
}, {"id": "7","pid": "0","class_name": "旅游商品","basic_code": "G"
}, {"id": "8","pid": "0","class_name": "人文活动","basic_code": "H"
}, {"id": "198","pid": "0","class_name": "自然景观","basic_code": "I"
}]
4、总结
(1)、$(function(){});
在页面加载完成后进行操作。
(2)、$.ajax({});
的使用,获取到数据后写的for循环
(3)、对empty()
和append()
的使用