The sixth lesson of JQuery learning is to implement an AJAX Treeview_jquery

Source: Internet
Author: User
Tags bool tojson
The effect of the final implementation is a catalog file viewer, as shown in the figure:

The principle is that when a user clicks a directory, the path to the directory is sent to the server side, and the server returns the file and directory information in the directory. On the server side, define a class that represents the file information to be passed:
Copy Code code 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
}
}

Where FullPath is the full path to the file, which is used to get its subfolder/file, name is the name of the file, for display, Isfolder is to distinguish whether this data is a file or a folder so that it can be displayed with a different icon, and the last info is some additional information, Not used in this example. The C # code that obtains the file information in a directory from one path is simple and is posted here:
Copy Code code 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 further information goes here"
});
}
foreach (FileInfo f in info.) GetFiles ())
{
Res. ADD (New Fileinformation
{
FullPath = F.fullname,name = F.name,isfolder = False,
Info = "Any further information goes here"
});
}
}
return res;
}
}

This example uses the format of JSON data to pass this information. So you want to serialize the data. In. Net 3.5, there are ready-made classes that serialize entity classes into JSON data, using the following methods
Copy Code code 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 you are. NET 2.0, you can find some third-party components and it's no bother to write one yourself.
At this point, the main server-side work has been completed. Create a new Genric handler file, Filelist.ashx, code as follows, a simple response to the request, the output data can be:
Copy Code code 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;
}
}
}

Consider writing the client-side HTML code below. The main thing is two events, that is, the mouse clicks to send an AJAX request, processing the returned JSON data to generate HTML code, click the mouse again to empty the HTML code. Here, using the UL Li to display the TreeView, there is an invisible span in Li, which contains the complete path to the file, which will be used as the parameter to initiate the AJAX request, but is not visible to the user.
The HTML code is simple, just 4 lines:
Copy Code code as follows:

<body>
<ul>
</ul>
</body>

First you need to initialize a root directory, such as D:, the code is as follows:
Copy Code code as follows:

$ (function () {
$ (' <li class= ' folder ' >d:\\<span class= ' fullpath ' >D:\\</span></li> '). Appendto (' ul ');
$ (' li '). Hover (function () {
$ (this). CSS (' cursor ', ' pointer ');
},
Function () {$ (this). CSS (' cursor ', ' Default ');};
$ (' Li.folder '). Toggle (LoadFile, closefolder);
});

Constructs one Li node, adds to the UL to go, then sets down the mouse action the style, finally for its binding event handler, LoadFile and Closefolder.
Copy Code code as follows:

function LoadFile (event) {
if (this = = Event.target) {
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> '). AddClass (' folder '). html (this. Name). Append ($ (' <span> '). addclass (' FullPath '). HTML (this. FullPath)));
}
else {
Node.append (' <li> '). addclass (' file '). html (this. Name). Append ($ (' <span> '). addclass (' FullPath '). HTML (this. FullPath)));
}
});
Node.find (' Li.folder '). Toggle (LoadFile, closefolder);
});
}
}

The first thing to determine is whether the target of the event and this is the same object, to avoid multiple triggers when you click on the child node event to float. First, use the Find and HTML functions to get the full path. Construct a UL node and add it to the current LI. At this time the UL is empty, then initiates the AJAX request, obtains the server side the data. Generates an Li for each piece of data, which determines whether it is a directory, generates an Li with a different class, and adds it to node. Finally, don't forget to bind the event handler for the new node as well. The code is simpler, and the code to close the directory node is much simpler.
Copy Code code as follows:

function Closefolder (event) {
if (this = = Event.target)
$ (this). Find (' ul '). Remove ();
}

This example is complete. There are a few more CSS, no longer listed.
This example implements the features and styles are rough, but on this basis to do more expansion and beautification is not difficult. For example, you can add a little ready-made animation effect:
Copy Code code as follows:

function Closefolder (event) {
if (this = = Event.target) {
var node = $ (this). Find (' ul ');
Node.hide (' Slow ', function () {$ (this). Find (' ul '). Remove ();});
}
}

Hide first, then delete. Similarly, can be loaded immediately after the hidden, and then fade out.
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.