JQuery learning Lesson 6 Implementing a Ajax TreeView

Source: Internet
Author: User
Tags tojson

The final result is a directory File Viewer ,:

The principle is that when you click a directory, the path of the directory is sent to the server, and the server returns the file and directory information in the directory. On the server side, define the following class to indicate the file information to be transmitted: Copy codeThe Code is as follows: public class FileInformation
{
Public string FullPath
{
Get; set;
}
Public string Name
{
Get; set;
}
Public string Info
{
Get; set;
}
Public bool IsFolder
{
Get; set;
}
}

FullPath is the complete path of the file. It is used to obtain its subfolders/files. Name is the Name of the file for display. IsFolder distinguishes whether the data is a file or a folder, different icons are used for display. The last Info is some additional information, which is not used in this example. C # code for obtaining file information in a directory based on a path is very simple. It will be pasted here by the way:Copy codeThe Code is as follows: public class FileManager
{
Public static List <FileInformation> GetFolderContent (string fullpath)
{
List <FileInformation> res = new List <FileInformation> ();
DirectoryInfo info = new DirectoryInfo (fullpath );
If (info. Exists)
{
Foreach (DirectoryInfo d in info. GetDirectories ())
{
Res. Add (new FileInformation
{
FullPath = d. FullName, Name = d. Name, IsFolder = true,
Info = "Any More Information goes here"
});
}
Foreach (FileInfo f in info. GetFiles ())
{
Res. Add (new FileInformation
{
FullPath = f. FullName, Name = f. Name, IsFolder = false,
Info = "Any More Information goes here"
});
}
}
Return res;
}
}

In this example, the information is transmitted in JSON format. Therefore, we need to serialize the data. In. Net 3.5, there are ready-made classes that serialize object classes into JSON data. The usage is as follows:Copy codeThe Code is as follows: public static string ToJson <T> (T obj)
{
DataContractJsonSerializer d = new DataContractJsonSerializer (typeof (T ));
System. IO. MemoryStream MS = new System. IO. MemoryStream ();
D. WriteObject (MS, obj );
String strJSON = System. Text. Encoding. UTF8.GetString (ms. ToArray ());
Ms. Close ();
Return strJSON;
}

If it is. net 2.0, you can find some third-party components and write one by yourself.
So far, the main work on the server has been completed. Create a Genric Handler file, filelist. ashx. The Code is as follows. simply respond to the request and output the data:Copy codeThe Code is as follows: public class FileList: IHttpHandler {
Public void ProcessRequest (HttpContext context ){
String path = context. Request. QueryString ["path"];
String data = JsonHelper. ToJson <List <FileInformation> (FileManager. GetFolderContent (path ));
Context. Response. Write (data );
}
Public bool IsReusable {
Get {
Return false;
}
}
}

The following describes how to write the html code of the client. The most important thing is two events, that is, sending an ajax request by clicking the mouse, processing the returned json data to generate html code, and clicking the mouse again to clear the html code. Here, ul li is used to display this treeview. There is an invisible span in li, which contains the complete path of the file. It will be used as a parameter to initiate an ajax request, but it is invisible to users.
HTML code is simple, just four lines:Copy codeThe Code is as follows: <body>
<Ul>
</Ul>
</Body>

First, you need to initialize a root directory, such as D:. The Code is as follows:Copy codeThe Code is as follows: $ (function (){
$ ('<Li class = "folder"> D :\\ <span class = "fullpath"> D :\</span> </li> '). appendTo ('ul ');
$ ('Lil'). hover (function (){
Vertex (this).css ('cursor ', 'pointer ');
},
Function () {iterator (this).css ('cursor ', 'default ');});
$ ('Li. folder'). toggle (LoadFile, CloseFolder );
});

Create a li node, add it to ul, set the mouse action style, and bind the event handler, LoadFile, and CloseFolder.Copy codeThe Code is as follows: function LoadFile (event ){
If (this = event.tar get ){
Var path = (this).find('span'{.html ();
Var node = $ ('<ul> ');
$ (This). append (node );
$. GetJSON ('filelist. ashx', {path: path}, function (data ){
$. Each (data, function (){
If (this. IsFolder ){
Node. append ($ ('<li> 'your .addclass('folder'your .html (this. Name). append ($ (' <span> 'your .addclass('fullpath'your .html (this. FullPath )));
}
Else {
Node. append ($ ('<li> 'hangzhou.addclass('file'hangzhou.html (this. Name). append ($ (' <span> 'hangzhou.addclass('fullpath'hangzhou.html (this. FullPath )));
}
});
Node. find ('Li. folder'). toggle (LoadFile, CloseFolder );
});
}
}

First, you must determine whether the target and this of the event are the same object to avoid multiple triggers when the subnode event is clicked. First, use the find and html functions to obtain the complete path. Construct a ul node and add it to the current li node. In this case, ul is empty. Then, an ajax request is initiated to obtain data from the server. Generate a li for each piece of data. Determine whether the li is a directory, generate a li with different classes, and then add it to the node. Finally, do not forget to bind an event handler to the newly added node. The code is relatively simple. The code for disabling directory nodes is simpler,Copy codeThe Code is as follows: function CloseFolder (event ){
If (this = event.tar get)
$ (This). find ('ul '). remove ();
}

This example has been completed. A few more css statements are missing and will not be listed.
The functions and styles implemented in this example are rough, but it is not difficult to do more expansion and beautification on this basis. For example, you can add an existing animation effect:Copy codeThe Code is as follows: function CloseFolder (event ){
If (this = event.tar get ){
Var node = $ (this). find ('ul ');
Node. hide ('slow', function () {$ (this). find ('ul '). remove ();});
}
}

Hide and then delete. Similarly, you can hide and fade out immediately after loading.

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.