This article will introduce you to the code that uses jquery ajax and php to implement a drop-down list without any new linkage effects. If you need to know about it, you can refer to it.
For today's work, we need to write a tree-like linkage, So we wrote a scalable infinitus linkage drop-down option.
Code writing is messy. mark is empty before sorting.
Fuck!
The company cannot even take a picture on QQ!
Paste database first
| Id |
Category_name category name |
Pid parent category id |
Orders sorting |
| 1 |
22223331 |
0 |
1 |
| 2 |
2222111 |
1 |
1 |
| 12 |
44444 |
11 |
0 |
| 5 |
2222 |
1 |
1 |
| 6 |
2222 |
1 |
1 |
| 11 |
333 |
2 |
0 |
| 13 |
555555 |
12 |
0 |
SMARTY for page code
| The Code is as follows: |
Copy code |
<Div id = "select"> <Select name = "category_1" id = "category_1" onChange = "change ('category _ 1');"> <Option> select a Category </option> <! -- {Foreach from = $ galleryCategory item = category} --> <Option value = "{$ category. id}" >{$ category. category_name} </option> <! -- {/Foreach} --> </Select> </Div>
|
$ GalleryCategory
The data PHP code is?
| The Code is as follows: |
Copy code |
$ SQL = "select * from yl_gallery_category where pid = 0 "; $ GalleryCategory = $ db-> query ($ SQL ); $ Smarty-> assign ("galleryCategory", $ galleryCategory ); |
It is easier to understand the original code used to wipe the buttocks of projects of resigned colleagues.
Then the key JS Code is function change (val ){
| The Code is as follows: |
Copy code |
Var str = val; // select id Var num; // current level
Var id; // category id Num = str. substr (9, 10 ); // Alert (num ); Var nownum = parseInt (num) + 1; // converts a string to a number. Id = $ ("#" + str + ""). val (); Var r =/^ [1-9] + [0-9] * $/; // positive integer If (! R. test (id )){ // Clear obsolete options $ ("Select"). each (function (index ){ If (index + 1> num ){ $ (This). remove (); } })
Return false; } Var url = 'gallery. php? Act = category & pid = '+ id; $. Ajax ({ Type: "POST ", Cache: false, Url: url, Datatype: 'json ', Timeout: 3000, Success: function (result ){ If (result! = 0 ){ Var html = "<select name = category _" + nownum + "id = category _" + nownum + "onChange = change ('category _" + nownum + "');> "; Html + = "<option> select a Category </option> "; Var datas = eval (result ); $. Each (datas, function (I, val ){ Html + = "<option value = '" + val. id + "'>" + val. category_name + "</option> "; }); Html + = "</select> ";
// Clear obsolete options $ ("Select"). each (function (index ){ If (index + 1> num ){ $ (This). remove (); } })
$ ("# Select"). append (html ); } Else {// clear obsolete options $ ("Select"). each (function (index ){ If (index + 1> num ){ $ (This). remove (); } })}
}, Error: false });
} |
PHP code for AJAX Data Retrieval
| The Code is as follows: |
Copy code |
$ SQL = "select * from yl_gallery_category where pid =". $ pid; $ Res = $ db-> query ($ SQL ); If (empty ($ res )){ $ Res = 0; } Echo json_encode ($ res );
|
OK!