Ajax cascading pull-down menu implemented with PHPRPC

Source: Internet
Author: User
Tags add functions sql php and sqlite sqlite database version javascript array
Ajax| Menu | dropdown

The cascading drop-down menu is when you select an item from a Drop-down menu, and the contents of the corresponding Drop-down menu change.

In general, the simplest is to submit a form every time you select it, refreshing the entire page. This is also the worst user experience.

The other is to load all the options into a JavaScript array in the entire page at the first load, then cascade through JavaScript, which is a nice way to achieve no refresh and fast when the whole amount of data is small, but when the whole amount of data is very large, This method causes the first load to become very slow.

There is the use of Ajax, that is, start loading only the contents of the first level menu, when the user selects an item in the first level menu, and then through the XMLHttpRequest to get the corresponding options for the second-level menu content. This works best, but the traditional way to write this kind of Ajax program code is much more. And if the design is not good, server-side return menu content of the program's reusability will also be very poor.

But in this article you will see how simple it is to use PHPRPC to achieve this Ajax effect, and that it will be highly reusable.


This article takes the provincial and municipal two cascade drop-down menu for example, for example, the SQLite database is used in this article because the file-type database is easier to deploy and the query is efficient (of course, the creation of the database is not efficient, but only once, the database is unchanged in the program), However, the server needs to install the SQLite extension.

There are only 2 tables in this database, one province table, one city table. Province table, only the ID and name two fields, respectively, are the province number (primary key) and provincial name. In the city table, there are three fields with ID, name, and PID, ID is town number, name is City name, PID is the number of the city province, correspond to the provincial number in the province table.

The program that created the database is not given here, it is included in the download of the instance provided later.

Let's look at how simple it is to create the server side of the program, and in order to improve reusability, we divide the server into 2 files, one is function.php and the other is rpc.php. The actual remote call functions are defined in function.php, but they can also be called as local functions on the server side, and you will find that they have nothing to do with the normal functions of the server side:

Download: function.php
<?php
$sqlite = new Sqlitedatabase (' area.db ');

function Get_province () {
Global $sqlite;
$sql = "SELECT * from Province order by id";
Return $sqlite->arrayquery ($sql, SQLITE_ASSOC);
}

function Get_city ($pid) {
Global $sqlite;
$pid = sqlite_escape_string ($pid);
$sql = "SELECT * from city where PID = $pid order by id";
Return $sqlite->arrayquery ($sql, SQLITE_ASSOC);
}
?>
And rpc.php is simpler, it is the interface that is provided to the client call, it has only 3 lines of statements:

Download: function.php
<?php
Require_once (' function.php ');
Require_once (' phprpc_server.php ');
New Phprpc_server (Array (' get_province ', ' get_city '));
?>
The last sentence is to specify which functions to expose to the client. Only the specified function client can be invoked, which guarantees the security of the server.

The server is done to create the end. You will find that the server is only responsible for the data query out to return to the client is done, the others do not do any processing.

Then the following should look at the client, although the client is very simple, but I still divided it into two files, a JS file, an HTML file, you will find that with PHPRPC, the client does not need to use PHP.

Download: area.js
Create Phprpc Client Object RPC
Phprpc_client.create (' RPC ');

var city = []; Used to cache loaded city data

/*
* Clear options in Select, this method can be reused
*
* So: Select object to clear options
*
*/
function Clear_select (SO) {
for (var i = so.options.length-1 i > 1; i--) {
Some browsers do not support the Remove method for the Options property.
But RemoveChild methods that support DOM (for example, Konqueror)
if (so.options.remove) {
So.options.remove (i);
}
else {
So.removechild (So.options[i]);
}
}
}

/*
* Set options in Select, which can be reused
*
* So: Select object to Set options
* d: Array of option data
* VF: The name of the field in the array corresponding to the option value
* TF: The name of the field in the array corresponding to the option text
*/
function Set_select (So, D, VF, TF) {
for (var i = 0, n = d.length i < n; i++) {
var opt = document.createelement (' option ');
Opt.text = D[I][TF];
Opt.value = D[I][VF];
Some browsers do not support the Add method for the options attribute.
But appendchild methods that support DOM (for example, Konqueror)
if (So.options.add) {
So.options.add (opt);
}
else {
So.appendchild (opt);
}
}
}

Set the province's Drop-down menu
function Set_province_select (d) {
var so = document.getElementById (' province ');
Set_select (So, d, ' id ', ' name ');
Set up city Drop-down lists for preferred provinces
Change_province (1);
}

Set the Drop-down menu for the city
function Set_city_select (d, VF, TF) {
var so = document.getElementById (' city ');
Empty original option
Clear_select (SO);
Set new options
Set_select (So, D, VF, TF);
}

When the provinces change, the corresponding changes to the city list
function Change_province (PID) {
If cached, displays the list directly in the cache
if (City[pid]) {
Set_city_select (City[pid], ' id ', ' name ');
}
else {
Otherwise, first show the load in
Set_city_select ([[', ' Loading ... ']], 0, 1);
Then call the remote procedure to load the city information
When a remote procedure is invoked, the last parameter specifies a callback function
Rpc.get_city (PID, function (Result) {
Put the loaded data into the cache
CITY[PID] = result;
Update City List
Set_city_select (result, ' id ', ' name ');
});
}
}

Define what to do when RPC client initialization (Use_service) completes
Rpc.onready = function () {
Call the remote procedure that gets the province content and set the callback function to Set_province_select
Rpc.get_province (Set_province_select);
}
Download: index.html
<script type= "Text/javascript" src= "Phprpc_client.js" ></script>
<script type= "Text/javascript" src= "Area.js" ></script>
<body >
<select id= "province" ></select>
<select id= "City" ></select>
</body>
The above HTML contains the Phprpc_client.js is a compressed version (because you do not need to use encryption, this is the Lite compression version), so you can eliminate the trouble of containing multiple JS files.

You will find that this program not only reusable good (such as Clear_select and set_select two functions can also be used in other programs), but also make the whole process of thinking clearly, such as the caching function, here is very simple, and the effect is very good.

  • Demo Program
  • Instance Downloads
  • Through PHPRPC, you do not need to focus on server-side and client data format Exchange, do not need to consider the creation and use of XMLHttpRequest objects, PHPRPC will automatically help you accomplish all of this, you only need to focus on specific issues. Using PHPRPC to do Ajax programming is that simple.



    Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.