1. 首先使用AJAX
整个页面获取数据的方式是Ajax实现的,在Joomla中,Ajax的实现方法是在module中写一个ajax的方法。在前端的js代码中,只要按照Joomla的规范发送相应的request就可以了。这里是Joomla Ajax的官方文档。
下面是我在JS端发送Ajax的代码:
/**
* This is the callback function to handle the data,
* When jQuery ajax successfully received data.
* @param {obj} request
* @param {obj} handleResponse
* @returns {obj} XMLHttpRequest
*/
function useAjax(request, handleResponse) {
return $.ajax({
type: 'POST',
data: request,
success: function (response) {
handleResponse(response);
}
});
}
/**
* Setup jQuery ajax request to get homes.
* @param {string} schoolLevel
* @param {string} schoolType
* @param {string} city
* @param {int} numberOfMoreSchools
* @param {int} numberOfSchoolsDisplayed
* @returns {obj} XMLHttpRequest
*/
function displayHomes(city, home_type, home_age, home_price, home_bedroom, home_bathroom, home_listingDate, home_area, keywords, numberOfMoreHomes, numberOfHomesDisplayed) {
var request = {
'option': 'com_ajax',
'module': 'houselist_mobile_cn',
'method': 'getHomes',
'data': {city: city, home_type: home_type, home_age: home_age, home_price: home_price, home_bedroom: home_bedroom, home_bathroom: home_bathroom, home_listingDate: home_listingDate, home_area: home_area, keywords: keywords, numberOfMoreHomes: numberOfMoreHomes, numberOfHomesDisplayed: numberOfHomesDisplayed},
'format': 'JSON'
};
return useAjax(request, function (response) {
var allhomes = JSON.parse(response.data);
console.log(allhomes);
var addHomes = '';
var imgUrl = '../images/ahome.png';
for (var j = 0; j < allhomes.length; j++) {
addHomes += '' +
allhomes[j].address + //'+score:'+allhomes[j].sorting_score+
'' +
allhomes[j].bedrooms +
'卧' +
(Number(allhomes[j].fullbaths) + Number(allhomes[j].halfbaths)) +
'卫 | ' +
allhomes[j].floor_area +
'平方公尺 | ' +
allhomes[j].city +
'' +
allhomes[j].dwelling_type +
'' +
Math.round(allhomes[j].list_price / 10000) +
'万';
}
$("#homes").append(addHomes);
});
}
主要注意的是displayHome方法中request一定要符合Joomla的规范。
var request = {
'option': 'com_ajax',
'module': 'houselist_mobile_cn',
'method': 'getHomes',
'data': {city: city, home_type: home_type, home_age: home_age, home_price: home_price, home_bedroom: home_bedroom, home_bathroom: home_bathroom, home_listingDate: home_listingDate, home_area: home_area, keywords: keywords, numberOfMoreHomes: numberOfMoreHomes, numberOfHomesDisplayed: numberOfHomesDisplayed},
'format': 'JSON'
};
2. Module中model里面的PHP方法
这个方法就是取得符合ajax请求条件的房子就可以了。下面是代码,注意方法名字最后必须有Ajax这四个字。
public function getHomesAjax() {
$city = $_POST['data']['city'];
$home_type = $_POST['data']['home_type'];
$home_age=$_POST['data']['home_age'];
$home_price=$_POST['data']['home_price'];
$home_bedroom=$_POST['data']['home_bedroom'];
$home_bathroom=$_POST['data']['home_bathroom'];
$home_listingdate =$_POST['data']['home_listingDate'];
$home_area=$_POST['data']['home_area'];
$keywords=$_POST['data']['keywords'];
$numberOfMoreHomes=$_POST['data']['numberOfMoreHomes'];
$numberOfHomesDisplayed=$_POST['data']['numberOfHomesDisplayed'];
$db =JDatabaseDriver::getInstance(__DTBS2__);
//city
if(empty($city)){
$city = "city='Vancouver'";
}else{
$city = "city='".$city."'";
}
//home types
$home_types='';
if(!empty($home_type)){
foreach ($home_type as $k => $v){
switch($v){
case 'apartment':
$home_types.=(' || dwelling_type like "%apartment%" || dwelling_type like "%condo%"');
break;
case 'house':
$home_types.=(' || dwelling_type like "house%" || dwelling_type like "%single family%" || dwelling_type like "%acreage%" || dwelling_type like "%raw%"');
break;
case 'townhouse':
$home_types.=(' || dwelling_type like "%townhouse%" || dwelling_type like "%Duplex%" || dwelling_type like "%1/2 Duplex%" || dwelling_type like "%Triplex%" || dwelling_type like "%Fourplex%"');
break;
default:
$home_types.=(' || dwelling_type like "%other%" || dwelling_type like "%manufactured%" || dwelling_type like "%recreational%"');
break;
}
}
if($home_types) $home_types=' ('.substr($home_types,4,strlen($home_types)).')';
}
// home age
if($home_age==26){
$builtyear=" yearbuilt<".(date("Y")-25);
} else if($home_age>=0){
$builtyear=" yearbuilt>=".(date("Y")-(int)$home_age);
}else{
$builtyear='';
}
// price
if($home_price[0]>0 && $home_price[1]>0){
$prices=" list_price>=".($home_price[0]*10000)." AND list_price<".($home_price[1]*10000);
}else if($home_price[0]>0 && !$home_price[1]){
$prices=" list_price>=".($home_price[0]*10000);
}else if(!$home_price[0] && $home_price[1]>0){
$prices=" list_price<".($home_price[1]*10000);
}else{
$prices='';
}
//bedroom
if($home_bedroom==6){
$bedroom=" bedrooms>5";
} else if($home_bedroom>0){
$bedroom=" bedrooms=".$home_bedroom;
}else{
$bedroom='';
}
// bathroom
if($home_bathroom==6){
$bathroom=" group by(record_id) having sum(fullbaths+halfbaths)>5";
}else if($home_bathroom>0){
$bathroom=" group by(record_id) having sum(fullbaths+halfbaths)=".$home_bathroom;
}else{
$bathroom='';
}
// listing date
$currentday=date("Y-m-d");
if($home_listingdate){
switch($home_listingdate){
case .1:
$listing_date=" listing_date='".$currentday."'";
break;
case .25:
$past7day=date("Y-m-d",strtotime("-7 days,".$currentday));
$listing_date=" listing_date>'".$past7day."' listing_date<='".$currentday."'";
break;
case 4:
$listing_date=" listing_date<='".$currentday."'";
break;
default:
$pastday=date("Y-m-d",strtotime("- ".$home_listingdate." months,".$currentday));
$listing_date=" listing_date>'".$pastday."' listing_date<='".$currentday."'";
break;
}
}else{
$listing_date='';
}
//area
if($home_area[0]>0 && $home_area[1]>0){
$areas=" floor_area>=".$home_area[0]." AND floor_area<".$home_area[1];
}else if($home_area[0]>0 && !$home_area[1]){
$areas=" floor_area>=".$home_area[0];
}else if(!$home_area[0] && $home_area[1]>0){
$areas=" floor_area<".$home_area[1];
}else{
$areas='';
}
$query = $db->getQuery(true)
->select('a.record_id, a.mls_id,a.list_price,a.address,a.city,a.postal_code,a.dwelling_type,a.listing_date,a.floor_area,a.lot_size,a.yearbuilt,a.bedrooms,a.fullbaths,a.halfbaths, b.sorting_score')
->from('mls_data as a')
->leftJoin('listing_additional as b on a.mls_id=b.mls_id')
->where('listing_status = "Active"')
->where($city)
->where($home_types?$home_types:'1')
->where($prices?$prices:'1')
->where($builtyear?$builtyear:'1')
->where($bedroom?$bedroom:'1')
->where($bathroom?$bathroom:'1')
->where($listing_date?$listing_date:'1')
->where($areas?$areas:'1')
->order('sorting_score DESC')
->setLimit($numberOfMoreHomes, $numberOfHomesDisplayed);
$allhomes=$db->setQuery($query)->loadObjectList();
return json_encode($allhomes);
}
- 关于筛选条件。
我的筛选条件都是在一个form里面,每一个筛选条件都是一个input。当用户输入或者选了东西的时候,form中存放的value会响应的变化,代码太多,我就只粘贴其中一个filter。
// price
//即时判断最小价格输入情况
document.getElementById('price-min').oninput = function () {
if (document.forms['filterForm'].home_price_min.value) {
if (!floatReg.test(document.forms['filterForm'].home_price_min.value)) {
document.getElementById('price-warning').innerHTML = '最低价格输入格式不正确!';
filterPriceFlag = false;
} else if (document.forms['filterForm'].home_price_min.value && Number(document.forms['filterForm'].home_price_max.value) && Number(document.forms['filterForm'].home_price_max.value) < Number(document.forms['filterForm'].home_price_min.value)) {
document.getElementById('price-warning').innerHTML = '房屋最高价格应高于或等于最低价格!';
filterPriceFlag = false;
} else {
document.getElementById('price-warning').innerHTML = '';
filterPriceFlag = true;
}
} else if (document.forms['filterForm'].home_price_max.value && !floatReg.test(document.forms['filterForm'].home_price_max.value)) {
document.getElementById('price-warning').innerHTML = '最高价格输入格式不正确!';
filterPriceFlag = false;
} else {
document.getElementById('price-warning').innerHTML = '';
filterPriceFlag = true;
}
if (document.forms['filterForm'].home_price_max.value && !floatReg.test(document.forms['filterForm'].home_price_max.value)) {
document.getElementById('price-warning').innerHTML = '最高价格输入格式不正确!';
filterPriceFlag = false;
}
};
//即时判断最大价格输入情况
document.getElementById('price-max').oninput = function () {
if (document.forms['filterForm'].home_price_max.value) {
if (!floatReg.test(document.forms['filterForm'].home_price_max.value)) {
document.getElementById('price-warning').innerHTML = '最高价格输入格式不正确!';
filterPriceFlag = false;
} else if (document.forms['filterForm'].home_price_min.value && Number(document.forms['filterForm'].home_price_max.value) && Number(document.forms['filterForm'].home_price_max.value) < Number(document.forms['filterForm'].home_price_min.value)) {
document.getElementById('price-warning').innerHTML = '房屋最高价格应高于或等于最低价格!';
filterPriceFlag = false;
} else {
document.getElementById('price-warning').innerHTML = '';
filterPriceFlag = true;
}
} else if (document.forms['filterForm'].home_price_min.value && !floatReg.test(document.forms['filterForm'].home_price_min.value)) {
document.getElementById('price-warning').innerHTML = '最低价格输入格式不正确!';
filterPriceFlag = false;
} else {
document.getElementById('price-warning').innerHTML = '';
filterPriceFlag = true;
}
if (document.forms['filterForm'].home_price_min.value && !floatReg.test(document.forms['filterForm'].home_price_min.value)) {
document.getElementById('price-warning').innerHTML = '最低价格输入格式不正确!';
filterPriceFlag = false;
}
};
//Click事件,给表单赋值
$("#price li").click(
function () {
if ($(".price-selected").length === 0) {
$(this).addClass("price-selected");
} else {
$(".price-selected").removeClass("price-selected");
$(this).addClass("price-selected");
}
switch ($(this).html()) {
case '不限':
document.forms['filterForm'].home_price_min.value = '';
document.forms['filterForm'].home_price_max.value = '';
//document.forms['filterForm'].submit();
break;
case '50万以内':
document.forms['filterForm'].home_price_min.value = 1;
document.forms['filterForm'].home_price_max.value = 50;
break;
case '500万+':
document.forms['filterForm'].home_price_min.value = 500;
document.forms['filterForm'].home_price_max.value = '';
break;
default:
var prices = $(this).html().split('-');
document.forms['filterForm'].home_price_min.value = Number(prices[0].replace('万', ''));
document.forms['filterForm'].home_price_max.value = Number(prices[1].replace('万', ''));
break;
}
$("#price-lb").html($(this).html() == '不限' ? '价格' : $(this).html());
});
最后,用户点击确认的时候就发送Ajax请求就可以了。这是手机端的逻辑,如果是网页版的话,可能要把AJAX的请求放在每一个click事件中.
// submit
$("#submit-filter").click(function (e) {
e.preventDefault();
$(".home-list-item").remove();
if (!filterPriceFlag) {
document.getElementById("price-lb").scrollIntoView();
} else if (!filterAreaFlag) {
document.getElementById("area-lb").scrollIntoView();
} else {
$("#filter-list").css("display", "none");
$("#loader").show();
alert(getHomeTypes());
displayHomes(city,getHomeTypes(), document.forms['filterForm'].home_age.value, [document.forms['filterForm'].home_price_min.value, document.forms['filterForm'].home_price_max.value], document.forms['filterForm'].home_bedroom.value, document.forms['filterForm'].home_bathroom.value, document.forms['filterForm'].home_listingDate.value, [document.forms['filterForm'].home_area_min.value, document.forms['filterForm'].home_area_max.value], document.forms['filterForm'].keywords.value, numberOfMoreHomes, numberOfHomesDisplayed).done(function(){
$("#loader").hide();
});
}
});
基本原理就是,表单存放筛选条件----->事件触发发送Ajax请求---->服务器端获得请求后在Ajax的callback中处理--->最后渲染页面.