使用jQuery创建Ajaxy链式选择

practice of using chainedSelects
practice of using chainedSelects

AJAX chained selects with jQuery. Today we will talk about creating dependent (chained) selects for your projects. This can be any related elements at your website. As example dependent fields to select your profession, mobile phone, or location (which can include Country, State, Region etc). One important note – we will need all this working using AJAX technology (to make functionality fast and smooth). And, jQuery library provide us with that plugin – jquery.chainedSelects.js. I will show you how to create chained fields using this plugin.

AJAX链式选择与jQuery。 今天,我们将讨论为您的项目创建依赖(链接)选择。 这可以是您网站上的任何相关元素。 例如,相关字段用于选择您的职业,手机或位置(可以包括国家,州,地区等)。 一个重要的注意事项–我们将需要使用AJAX技术进行所有这些工作(以使功能快速,流畅)。 而且,jQuery库为我们提供了该插件– jquery.chainedSelects.js。 我将向您展示如何使用此插件创建链接字段。

现场演示

[sociallocker]

[社交储物柜]

打包下载

[/sociallocker]

[/ sociallocker]

Ok, download the example files and lets start coding !

好的,下载示例文件并开始编码!

步骤1. SQL (Step 1. SQL)

We will keep our data in database (tables with countries, states and regions). I don`t will show you FULL sql here (its pretty big), but I will show you structures and few records per table. Full SQL will available in package (check for sql.sql file inside package). As you can see – I selected prefix ‘s85’ for tables – this is number of our current tutorial. You always can use your own table names if you wish.

我们会将数据保存在数据库中(包含国家,州和地区的表格)。 我不会在这里向您显示FULL SQL(它相当大),但是我将向您显示结构和每个表很少的记录。 完整SQL将在软件包中可用(检查软件包中的sql.sql文件)。 如您所见-我为表选择了前缀's85'-这是我们当前教程的编号。 如果愿意,您始终可以使用自己的表名。


-- countries
CREATE TABLE `s85_countries` (
  `country_code` varchar(2) NOT NULL,
  `country_name` varchar(255) NOT NULL,
  PRIMARY KEY  (`country_code`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;
INSERT INTO `s85_countries` (`country_code`, `country_name`) VALUES
('AR', 'Argentina'),
('AU', 'Australia'),
('BR', 'Brazil');
-- states
CREATE TABLE `s85_states` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `country_code` varchar(3) NOT NULL,
  `state_name` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;
INSERT INTO `s85_states` (`id`, `country_code`, `state_name`) VALUES
(1, 'US', 'alabama'),
(2, 'US', 'alaska'),
(3, 'US', 'arizona');
-- regions
CREATE TABLE `s85_regions` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `state_id` int(11) NOT NULL,
  `region_name` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;
INSERT INTO `s85_regions` (`id`, `state_id`, `region_name`) VALUES
(1, 1, 'auburn'),
(2, 1, 'birmingham'),
(3, 1, 'columbus, GA');

-- countries
CREATE TABLE `s85_countries` (
  `country_code` varchar(2) NOT NULL,
  `country_name` varchar(255) NOT NULL,
  PRIMARY KEY  (`country_code`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;
INSERT INTO `s85_countries` (`country_code`, `country_name`) VALUES
('AR', 'Argentina'),
('AU', 'Australia'),
('BR', 'Brazil');
-- states
CREATE TABLE `s85_states` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `country_code` varchar(3) NOT NULL,
  `state_name` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;
INSERT INTO `s85_states` (`id`, `country_code`, `state_name`) VALUES
(1, 'US', 'alabama'),
(2, 'US', 'alaska'),
(3, 'US', 'arizona');
-- regions
CREATE TABLE `s85_regions` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `state_id` int(11) NOT NULL,
  `region_name` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;
INSERT INTO `s85_regions` (`id`, `state_id`, `region_name`) VALUES
(1, 1, 'auburn'),
(2, 1, 'birmingham'),
(3, 1, 'columbus, GA');

步骤2. PHP (Step 2. PHP)

index.php (index.php)

This is our main PHP file, I using this file to generate our FORM with necessary selects for country, state and region fields. And, this file also contain code for ajax calls of states (of selected country) and regions (of selected state).

这是我们的主要PHP文件,我使用该文件生成带有针对国家,州和地区字段的必要选择的FORM。 并且,该文件还包含用于州(选定国家)和区域(选定州)的ajax调用的代码。


<?
require_once('classes/CMySQL.php');
if (version_compare(phpversion(), "5.3.0", ">=")  == 1)
  error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
else
  error_reporting(E_ALL & ~E_NOTICE);
// return states of country
if ($_GET['action'] == 'get_states') {
    $sCountryName = $GLOBALS['MySQL']->escape($_GET['_value']);
    $aRet[] = array(0 => 'any');
    $aStates = $GLOBALS['MySQL']->getPairs("SELECT * FROM `s85_states` WHERE `country_code`='{$sCountryName}'", 'id', 'state_name');
    foreach ($aStates as $iStateId => $sStateName) {
        $aRet[] = array($iStateId => $sStateName);
    }
    echo json_encode($aRet);
    exit;
}
if ($_GET['action'] == 'get_regions') {
    $iStateID = (int)$_GET['_value'];
    $aRet[] = array(0 => 'any');
    $aRegions = $GLOBALS['MySQL']->getPairs("SELECT * FROM `s85_regions` WHERE `state_id`='{$iStateID}'", 'id', 'region_name');
    foreach ($aRegions as $iRegionId => $sRegionName) {
        $aRet[] = array($iRegionId => $sRegionName);
    }
    echo json_encode($aRet);
    exit;
}
$sCountryOptions = '';
$aCountries = $GLOBALS['MySQL']->getPairs("SELECT * FROM `s85_countries`", 'country_code', 'country_name');
foreach ($aCountries as $sCode => $sName) {
    $sCountryOptions .= '<option value="'.$sCode.'">'.$sName.'</option>';
}
$sCountries = '<select name="country" id="country">'.$sCountryOptions.'</select>';
echo <<<EOF
<link href="css/style.css" rel="stylesheet" type="text/css" />
<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/jquery.chainedSelects.js" type="text/javascript"></script>
<script src="js/main.js" type="text/javascript"></script>
<div class="example">
    <form action="" method="post">
        <div><label for="country">Country</label>{$sCountries}</div>
        <div><label for="state">State</label>
            <select name="state" id="state""><option value="0">any</option></select>
        </div>
        <div><label for="region">Region</label>
            <select name="region" id="region""><option value="0">any</option></select>
        </div>
        <div><input name="submit" type="submit" value="Send this info" /></div>
    </form>
</div>
EOF;
if ($_POST) {
    // draw debug information
    echo '<pre>';
    print_r($_POST);
    echo '</pre>';
}
?>

<?
require_once('classes/CMySQL.php');
if (version_compare(phpversion(), "5.3.0", ">=")  == 1)
  error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
else
  error_reporting(E_ALL & ~E_NOTICE);
// return states of country
if ($_GET['action'] == 'get_states') {
    $sCountryName = $GLOBALS['MySQL']->escape($_GET['_value']);
    $aRet[] = array(0 => 'any');
    $aStates = $GLOBALS['MySQL']->getPairs("SELECT * FROM `s85_states` WHERE `country_code`='{$sCountryName}'", 'id', 'state_name');
    foreach ($aStates as $iStateId => $sStateName) {
        $aRet[] = array($iStateId => $sStateName);
    }
    echo json_encode($aRet);
    exit;
}
if ($_GET['action'] == 'get_regions') {
    $iStateID = (int)$_GET['_value'];
    $aRet[] = array(0 => 'any');
    $aRegions = $GLOBALS['MySQL']->getPairs("SELECT * FROM `s85_regions` WHERE `state_id`='{$iStateID}'", 'id', 'region_name');
    foreach ($aRegions as $iRegionId => $sRegionName) {
        $aRet[] = array($iRegionId => $sRegionName);
    }
    echo json_encode($aRet);
    exit;
}
$sCountryOptions = '';
$aCountries = $GLOBALS['MySQL']->getPairs("SELECT * FROM `s85_countries`", 'country_code', 'country_name');
foreach ($aCountries as $sCode => $sName) {
    $sCountryOptions .= '<option value="'.$sCode.'">'.$sName.'</option>';
}
$sCountries = '<select name="country" id="country">'.$sCountryOptions.'</select>';
echo <<<EOF
<link href="css/style.css" rel="stylesheet" type="text/css" />
<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/jquery.chainedSelects.js" type="text/javascript"></script>
<script src="js/main.js" type="text/javascript"></script>
<div class="example">
    <form action="" method="post">
        <div><label for="country">Country</label>{$sCountries}</div>
        <div><label for="state">State</label>
            <select name="state" id="state""><option value="0">any</option></select>
        </div>
        <div><label for="region">Region</label>
            <select name="region" id="region""><option value="0">any</option></select>
        </div>
        <div><input name="submit" type="submit" value="Send this info" /></div>
    </form>
</div>
EOF;
if ($_POST) {
    // draw debug information
    echo '<pre>';
    print_r($_POST);
    echo '</pre>';
}
?>

Make attention, I using my own class for work with database – ‘classes/CMySQL.php’. This file already available in package. Commonly – you can use same, or similar class for your own projects. This just give some comfort with working with database. One thing what you will need to do – configure database connection parameters inside that file (in top of its code).

请注意,我使用自己的类来处理数据库-“ classes / CMySQL.php”。 该文件已在软件包中可用。 通常,您可以为自己的项目使用相同或相似的类。 这只是为使用数据库提供了一些便利。 您需要做的一件事–在该文件内(在其代码顶部)配置数据库连接参数。

步骤3. JS (Step 3. JS)

js / jquery.js和js / jquery.chainedSelects.js (js/jquery.js and js/jquery.chainedSelects.js)

This is just ordinary jQuery library with our new plugin – chainedSelects. Both files available in package.

这只是带有我们新插件– chainedSelects的普通jQuery库。 这两个文件都在软件包中可用。

js / main.js (js/main.js)

$(function() {
  $('select[name=country]').chainSelect('#state','index.php?action=get_states', {
    before:function (target) {
      $(target).css('visibility','hidden');
    },
    after:function (target) {
      $(target).css('visibility','visible');
    }
  });
  $('#state').chainSelect('#region','index.php?action=get_regions', {
    before:function (target) {
      $(target).css('visibility','hidden');
    },
    after:function (target) {
      $(target).css('visibility','visible');
    }
  });
});

$(function() {
  $('select[name=country]').chainSelect('#state','index.php?action=get_states', {
    before:function (target) {
      $(target).css('visibility','hidden');
    },
    after:function (target) {
      $(target).css('visibility','visible');
    }
  });
  $('#state').chainSelect('#region','index.php?action=get_regions', {
    before:function (target) {
      $(target).css('visibility','hidden');
    },
    after:function (target) {
      $(target).css('visibility','visible');
    }
  });
});

Syntax of chainedSelects using easy, we can point which URL will called when we changing selects, also we can perform some extra actions before request, and after.

使用easy的chainedSelects语法,我们可以指出更改选择时将调用哪个URL,也可以在请求之前和之后执行一些额外的操作。

步骤4. CSS (Step 4. CSS)

css / style.css (css/style.css)

body {
    background:#eee;
    margin:0;
    padding:0;
}
.example {
    background:#FFF;
    width:400px;
    border:1px #000 solid;
    margin:20px auto;
    padding:15px;
    -moz-border-radius:3px;
    -webkit-border-radius:3px;
}
.example form {
    background:#EEE;
    border:1px #DDD solid;
    padding:10px;
    -moz-border-radius:3px;
    -webkit-border-radius:3px;
}
.example form div {
    margin:10px;
}
.example form div label {
    display:block;
    width:100px;
    float:left;
}
.example form div select {
    width:200px;
}

body {
    background:#eee;
    margin:0;
    padding:0;
}
.example {
    background:#FFF;
    width:400px;
    border:1px #000 solid;
    margin:20px auto;
    padding:15px;
    -moz-border-radius:3px;
    -webkit-border-radius:3px;
}
.example form {
    background:#EEE;
    border:1px #DDD solid;
    padding:10px;
    -moz-border-radius:3px;
    -webkit-border-radius:3px;
}
.example form div {
    margin:10px;
}
.example form div label {
    display:block;
    width:100px;
    float:left;
}
.example form div select {
    width:200px;
}

现场演示

结论 (Conclusion)

In result, now we have pretty nice dependent selectors where we can choose our location. Happy coding. Good luck in your projects!

结果,现在我们有了不错的依赖选择器,可以在其中选择位置。 快乐的编码。 在您的项目中祝您好运!

翻译自: https://www.script-tutorials.com/creating-ajaxy-chained-selects-with-jquery/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值