文章目錄
- 0.效果展示
- 1.后端接口
- 2.前端js
- 3.前端html
0.效果展示
1.后端接口
house.py部分接口:
# GET /api/v1.0/houses?sd=2017-12-01&ed=2017-12-31&aid=10&sk=new&p=1
@api.route("/houses")
def get_house_list():"""獲取房屋的列表信息(搜索頁面)"""start_date = request.args.get("sd", "") # 用戶想要的起始時間end_date = request.args.get("ed", "") # 用戶想要的結束時間area_id = request.args.get("aid", "") # 區域編號sort_key = request.args.get("sk", "new") # 排序關鍵字page = request.args.get("p") # 頁數# 處理時間try:if start_date:start_date = datetime.strptime(start_date, "%Y-%m-%d")if end_date:end_date = datetime.strptime(end_date, "%Y-%m-%d")if start_date and end_date:assert start_date <= end_dateexcept Exception as e:current_app.logger.error(e)return jsonify(errno=RET.PARAMERR, errmsg="日期參數有誤")# 判斷區域idif area_id:try:area = Area.query.get(area_id)except Exception as e:current_app.logger.error(e)return jsonify(errno=RET.PARAMERR, errmsg="區域參數有誤")# 處理頁數try:page = int(page)except Exception as e:current_app.logger.error(e)page = 1# 獲取緩存數據redis_key = "house_%s_%s_%s_%s" % (start_date, end_date, area_id, sort_key)try:resp_json = redis_store.hget(redis_key, page)except Exception as e:current_app.logger.error(e)else:if resp_json:return resp_json, 200, {"Content-Type": "application/json"}# 過濾條件的參數列表容器filter_params = []# 填充過濾參數# 時間條件conflict_orders = Nonetry:if start_date and end_date:# 查詢沖突的訂單conflict_orders = Order.query.filter(Order.begin_date <= end_date, Order.end_date >= start_date).all()elif start_date:conflict_orders = Order.query.filter(Order.end_date >= start_date).all()elif end_date:conflict_orders = Order.query.filter(Order.begin_date <= end_date).all()except Exception as e:current_app.logger.error(e)return jsonify(errno=RET.DBERR, errmsg="數據庫異常")if conflict_orders:# 從訂單中獲取沖突的房屋idconflict_house_ids = [order.house_id for order in conflict_orders]# 如果沖突的房屋id不為空,向查詢參數中添加條件if conflict_house_ids:filter_params.append(House.id.notin_(conflict_house_ids))# 區域條件if area_id:filter_params.append(House.area_id == area_id)# 查詢數據庫# 補充排序條件if sort_key == "booking": # 入住做多house_query = House.query.filter(*filter_params).order_by(House.order_count.desc())elif sort_key == "price-inc":house_query = House.query.filter(*filter_params).order_by(House.price.asc())elif sort_key == "price-des":house_query = House.query.filter(*filter_params).order_by(House.price.desc())else: # 新舊house_query = House.query.filter(*filter_params).order_by(House.create_time.desc())# 處理分頁try:# 當前頁數 每頁數據量 自動的錯誤輸出page_obj = house_query.paginate(page=page, per_page=constants.HOUSE_LIST_PAGE_CAPACITY, error_out=False)except Exception as e:current_app.logger.error(e)return jsonify(errno=RET.DBERR, errmsg="數據庫異常")# 獲取頁面數據house_li = page_obj.itemshouses = []for house in house_li:houses.append(house.to_basic_dict())# 獲取總頁數total_page = page_obj.pagesresp_dict = dict(errno=RET.OK, errmsg="OK", data={"total_page": total_page, "houses": houses, "current_page": page})resp_json = json.dumps(resp_dict)if page <= total_page:# 設置緩存數據redis_key = "house_%s_%s_%s_%s" % (start_date, end_date, area_id, sort_key)# 哈希類型try:# redis_store.hset(redis_key, page, resp_json)# redis_store.expire(redis_key, constants.HOUES_LIST_PAGE_REDIS_CACHE_EXPIRES)# 創建redis管道對象,可以一次執行多個語句pipeline = redis_store.pipeline()# 開啟多個語句的記錄pipeline.multi()pipeline.hset(redis_key, page, resp_json)pipeline.expire(redis_key, constants.HOUES_LIST_PAGE_REDIS_CACHE_EXPIRES)# 執行語句pipeline.execute()except Exception as e:current_app.logger.error(e)return resp_json, 200, {"Content-Type": "application/json"}
2.前端js
search.js
var cur_page = 1; // 當前頁
var next_page = 1; // 下一頁
var total_page = 1; // 總頁數
var house_data_querying = true; // 是否正在向后臺獲取數據// 解析url中的查詢字符串
function decodeQuery(){var search = decodeURI(document.location.search);return search.replace(/(^\?)/, '').split('&').reduce(function(result, item){values = item.split('=');result[values[0]] = values[1];return result;}, {});
}// 更新用戶點選的篩選條件
function updateFilterDateDisplay() {var startDate = $("#start-date").val();var endDate = $("#end-date").val();var $filterDateTitle = $(".filter-title-bar>.filter-title").eq(0).children("span").eq(0);if (startDate) {var text = startDate.substr(5) + "/" + endDate.substr(5);$filterDateTitle.html(text);} else {$filterDateTitle.html("入住日期");}
}// 更新房源列表信息
// action表示從后端請求的數據在前端的展示方式
// 默認采用追加方式
// action=renew 代表頁面數據清空從新展示
function updateHouseData(action) {var areaId = $(".filter-area>li.active").attr("area-id");if (undefined == areaId) areaId = "";var startDate = $("#start-date").val();var endDate = $("#end-date").val();var sortKey = $(".filter-sort>li.active").attr("sort-key");var params = {aid:areaId,sd:startDate,ed:endDate,sk:sortKey,p:next_page};$.get("/api/v1.0/houses", params, function(resp){house_data_querying = false;if ("0" == resp.errno) {if (0 == resp.data.total_page) {$(".house-list").html("暫時沒有符合您查詢的房屋信息。");} else {total_page = resp.data.total_page;if ("renew" == action) {cur_page = 1;$(".house-list").html(template("house-list-tmpl", {houses:resp.data.houses}));} else {cur_page = next_page;$(".house-list").append(template("house-list-tmpl", {houses: resp.data.houses}));}}}})
}$(document).ready(function(){var queryData = decodeQuery();var startDate = queryData["sd"];var endDate = queryData["ed"];$("#start-date").val(startDate);$("#end-date").val(endDate);updateFilterDateDisplay();var areaName = queryData["aname"];if (!areaName) areaName = "位置區域";$(".filter-title-bar>.filter-title").eq(1).children("span").eq(0).html(areaName);// 獲取篩選條件中的城市區域信息$.get("/api/v1.0/areas", function(data){if ("0" == data.errno) {// 用戶從首頁跳轉到這個搜索頁面時可能選擇了城區,所以嘗試從url的查詢字符串參數中提取用戶選擇的城區var areaId = queryData["aid"];// 如果提取到了城區id的數據if (areaId) {// 遍歷從后端獲取到的城區信息,添加到頁面中for (var i=0; i<data.data.length; i++) {// 對于從url查詢字符串參數中拿到的城區,在頁面中做高亮展示// 后端獲取到城區id是整型,從url參數中獲取到的是字符串類型,所以將url參數中獲取到的轉換為整型,再進行對比areaId = parseInt(areaId);if (data.data[i].aid == areaId) {$(".filter-area").append('<li area-id="'+ data.data[i].aid+'" class="active">'+ data.data[i].aname+'</li>');} else {$(".filter-area").append('<li area-id="'+ data.data[i].aid+'">'+ data.data[i].aname+'</li>');}}} else {// 如果url參數中沒有城區信息,不需要做額外處理,直接遍歷展示到頁面中for (var i=0; i<data.data.length; i++) {$(".filter-area").append('<li area-id="'+ data.data[i].aid+'">'+ data.data[i].aname+'</li>');}}// 在頁面添加好城區選項信息后,更新展示房屋列表信息updateHouseData("renew");// 獲取頁面顯示窗口的高度var windowHeight = $(window).height();// 為窗口的滾動添加事件函數window.onscroll=function(){// var a = document.documentElement.scrollTop==0? document.body.clientHeight : document.documentElement.clientHeight;var b = document.documentElement.scrollTop==0? document.body.scrollTop : document.documentElement.scrollTop;var c = document.documentElement.scrollTop==0? document.body.scrollHeight : document.documentElement.scrollHeight;// 如果滾動到接近窗口底部if(c-b<windowHeight+50){// 如果沒有正在向后端發送查詢房屋列表信息的請求if (!house_data_querying) {// 將正在向后端查詢房屋列表信息的標志設置為真,house_data_querying = true;// 如果當前頁面數還沒到達總頁數if(cur_page < total_page) {// 將要查詢的頁數設置為當前頁數加1next_page = cur_page + 1;// 向后端發送請求,查詢下一頁房屋數據updateHouseData();} else {house_data_querying = false;}}}}}});$(".input-daterange").datepicker({format: "yyyy-mm-dd",startDate: "today",language: "zh-CN",autoclose: true});var $filterItem = $(".filter-item-bar>.filter-item");$(".filter-title-bar").on("click", ".filter-title", function(e){var index = $(this).index();if (!$filterItem.eq(index).hasClass("active")) {$(this).children("span").children("i").removeClass("fa-angle-down").addClass("fa-angle-up");$(this).siblings(".filter-title").children("span").children("i").removeClass("fa-angle-up").addClass("fa-angle-down");$filterItem.eq(index).addClass("active").siblings(".filter-item").removeClass("active");$(".display-mask").show();} else {$(this).children("span").children("i").removeClass("fa-angle-up").addClass("fa-angle-down");$filterItem.eq(index).removeClass('active');$(".display-mask").hide();updateFilterDateDisplay();}});$(".display-mask").on("click", function(e) {$(this).hide();$filterItem.removeClass('active');updateFilterDateDisplay();cur_page = 1;next_page = 1;total_page = 1;updateHouseData("renew");});$(".filter-item-bar>.filter-area").on("click", "li", function(e) {if (!$(this).hasClass("active")) {$(this).addClass("active");$(this).siblings("li").removeClass("active");$(".filter-title-bar>.filter-title").eq(1).children("span").eq(0).html($(this).html());} else {$(this).removeClass("active");$(".filter-title-bar>.filter-title").eq(1).children("span").eq(0).html("位置區域");}});$(".filter-item-bar>.filter-sort").on("click", "li", function(e) {if (!$(this).hasClass("active")) {$(this).addClass("active");$(this).siblings("li").removeClass("active");$(".filter-title-bar>.filter-title").eq(2).children("span").eq(0).html($(this).html());}})
})
3.前端html
search.html
<!DOCTYPE html>
<html>
<head> <meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"><title>愛家-房源</title><link href="/static/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet"><link href="/static/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet"><link href="/static/css/reset.css" rel="stylesheet"><link href="/static/plugins/bootstrap-datepicker/css/bootstrap-datepicker.min.css" rel="stylesheet"><link href="/static/css/ihome/main.css" rel="stylesheet"><link href="/static/css/ihome/search.css" rel="stylesheet">
</head>
<body><div class="container"><div class="top-bar"><div class="nav-bar"><h3 class="page-title">房 源</h3><a class="nav-btn fl" href="/"><span><i class="fa fa-angle-left fa-2x"></i></span></a></div><ul class="filter-title-bar"><li class="filter-title"><span>入住日期</span><span><i class="fa fa-angle-down"></i></span><span class="split-line fr">|</span></li><li class="filter-title"><span>位置區域</span><span><i class="fa fa-angle-down"></i></span><span class="split-line fr">|</span></li><li class="filter-title"><span>最新上線</span><span><i class="fa fa-angle-down"></i></span></li></ul><div class="filter-item-bar"><div class="filter-item filter-date"><div class="input-daterange input-group"><input type="text" class="input-sm form-control" id="start-date" /><span class="input-group-addon">至</span><input type="text" class="input-sm form-control" id="end-date" /></div></div><ul class="filter-item filter-area"></ul><ul class="filter-item filter-sort"><li class="active" sort-key="new">最新上線</li><li sort-key="booking">入住最多</li><li sort-key="price-inc">價格 低-高</li><li sort-key="price-des">價格 高-低</li></ul></div></div><div class="display-mask"></div><ul class="house-list"></ul><script id="house-list-tmpl" type="text/html">{{each houses as house}}<li class="house-item"><a href="/detail.html?id={{house.house_id}}"><img src="{{house.img_url}}"></a><div class="house-desc"><div class="landlord-pic"><img src="{{house.user_avatar}}"></div><div class="house-price">¥<span>{{(house.price/100.0).toFixed(0)}}</span>/晚</div><div class="house-intro"><span class="house-title">{{house.title}}</span><em>出租{{house.room_count}}間 - {{house.order_count}}次入住 - {{house.address}}</em></div></div></li>{{/each}}</script><div class="footer"><p><span><i class="fa fa-copyright"></i></span>愛家租房 享受家的溫馨</p></div></div><script src="/static/js/jquery.min.js"></script><script src="/static/plugins/bootstrap/js/bootstrap.min.js"></script><script src="/static/plugins/bootstrap-datepicker/js/bootstrap-datepicker.min.js"></script><script src="/static/plugins/bootstrap-datepicker/locales/bootstrap-datepicker.zh-CN.min.js"></script><script src="/static/js/template.js"></script><script src="/static/js/ihome/search.js"></script>
</body>
</html>