Jquery dynamic loading of image data exercise code

Source: Internet
Author: User

After studying jquery over the past few days, I feel the strength of this library and find a good book <sharp jquery>
Here, I just made a casual step. The photo list and two buttons are shown above. Click a small image to display a large image. When you click a button, you can view the images on the next page and the previous page.
Ideas:
1. First, create viewer.htm on the photo album page. The layout is simple. The picture is shown in the figure above and two buttons. below is the big picture.
2. Create a general processing program viewServer. ashx to process the request for viewing the photo page.
3. Then, of course, you need to use the database, including the image path, description, and other information. The path of each small image should correspond to a large image. When you click a small image, the image is loaded.
4. Data Transmission uses json to create a function for loading images. When the page is loaded or the left or right buttons are clicked, the image is loaded through ajax, pass the start and end numbers of the requested image to the background page,
After receiving the request information, the background page searches for the required image information in the database.
Effect

Implementation Code:
Viewer.htm
Copy codeThe Code is as follows:
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Title> my photos </title>
<Style type = "text/css">
# Top {width: 1000px; height: 100px; margin: auto ;}
# LeftBtn {width: 18px; text-align: left; height: 100px; float: left; background-image: url (images/left.jpg );}
# RightBtn {width: 18px; height: 100px; float: right; background-image: url (images/right.jpg );}
# SmallPhoto {text-align: center; float: left; margin-left: 10px; margin-right: 5px ;}
# BigPhoto {width: 1000px; height: 600px; text-align: center; margin: auto ;}
. Photo {width: 100px; height: 100px; cursor: pointer ;}
# Bottom {width: 1000px; height: 50px; margin: auto ;}
</Style>
<Script src = "./js/jquery-1.4.2.js" type = "text/javascript"> </script>
<Script type = "text/javascript">
$ (Function (){
LoadPhoto (); // page loading function. Nine images are displayed each time, and 1-9 is displayed during loading.
$ ("# Count"). text ("1 ");
$ ("# LeftBtn"). click (function (){
Var firstIndex = parseInt ($ ("# smallTr: first-child image"). attr ("id"), 10 );
If (firstIndex <= 1) {// if the first page is reached
Return;
}
Else {
Var startId = firstIndex-9;
Var endId = startId + 8;
$ ("# Count"). text (startId );
LoadPhoto (startId, endId );
}
});
$ ("# RightBtn"). click (function (){
Var sum = $ ("# sum"). text ();
Var lastIndex = parseInt ($ ("# smallTr: last-child image"). attr ("id"), 10 );
If (lastIndex> = parseInt (sum, 10) {// if the last page is reached
Return;
}
Else {
Var startId = lastIndex + 1;
Var endId = startId + 8;
$ ("# Count"). text (startId );
LoadPhoto (startId, endId );
}
});
});
// Obtain the total number of images
Function getCountPhoto (){
$. Post ("viewServer. ashx", {"action": "countPhoto"}, function (data, status ){
If (status! = "Success "){
Alert ("failed to load the total number of images! ");
}
Else {
$ ("# Sum"). text (data );
}
});
};
// The public function for loading images. The index ranges from startid to endId.
Function loadPhoto (startId, endId ){
$. Post ("viewServer. ashx ", {" startId ": startId," endId ": endId," action ":" getData "}, function (data, status) {// tell the background which images are needed
If (status! = "Success "){
Alert ("small image loading failed! ");
}
Else {
GetCountPhoto (); // get the total number of images
$ ("# SmallTr"). empty ();
Var photos = $. parseJSON (data); // use json to transmit data. json is refreshing.
For (var I = 0; I <photos. length; I ++ ){
Var photo = photos [I];
Var td = $ ("<td> </td> ");
$ ("# SmallTr"). append (td );
}
$ ("# Tmpimg"). attr ("src", "images/" + photos [0]. ImageUrl );
}
// Set the mouseover and click events for each small image
$ ("# SmallTr img"). mouseenter (function (){
$ (This). attr ("cursor", "pointer ");
})
. Click (function (){
$ ("# Count"). text ($ (this). attr ("id "));
$ ("# Tmpimg"). attr ("src", $ (this). attr ("src "));
});
});
};
// If the image loading is slow, the system prompts loading ....
$ ("# Loading"). ajaxStart (function (){
$ (This). show ();
})
. AjaxStop (function (){
$ (This). hide ();
});
</Script>
</Head>
<Body style = "text-align: center;">
<Form id = "form1" runat = "server">
<Div id = "top" style = "text-align: center">
<Input id = "leftBtn" type = "button"/>
<Div id = "smallPhoto">
<Table>
<Tr id = "smallTr">
</Tr>
</Table>
</Div>
<Input id = "rightBtn" type = "button"/>
</Div>
<Div id = "bigPhoto">
<Span style = "display: none;" id = "loading"> loading ..... </span> <br/>
</Div>
<Br/>
<Div id = "bottom">
<Span id = "sum" style = "visibility: visible;"> <strong> 0 </strong> </span>, current <span id = "count" style = "visibility: visible;"> <strong> 0 </strong> </span>
</Div>
</Form>
</Body>
</Html>

Viewserver. ashx:
Copy codeThe Code is as follows:
<% @ WebHandler Language = "C #" Class = "viewServer" %>
Using System;
Using System. Web;
Using System. Data. SqlClient;
Using System. Data;
Using System. Collections. Generic;
Public class viewServer: IHttpHandler
{
Public void ProcessRequest (HttpContext context)
{
Context. Response. ContentType = "text/plain ";
String action = context. Request ["action"]. ToString ();
If (action = "countPhoto") // count the total number of images
{
String SQL = "select count (*) from T_SmallPhotos ";
DataTable dt = sqlHelper. GetTable (SQL );
Int count = Convert. ToInt32 (dt. Rows [0] [0]);
Context. Response. Write (count. ToString ());
}
Else if (action = "getData") // request image data
{
String startId = context. Request ["startId"]. ToString ();
String endId = context. Request ["endId"]. ToString ();
// String sqlStr = "SELECT * FROM (SELECT id, [imageName], [imageUrl], [imageAlt], [notes], Row_Number () OVER (order by id) rownum FROM T_SmallPhotos) t WHERE t. rownum> = 1 AND t. rownum <= 5"
// This query statement is a little complicated and uses the window function.
String sqlStr = "SELECT * FROM (SELECT id, [imageName], [imageUrl], [imageAlt], [notes], Row_Number () OVER (order by id) rownum FROM T_SmallPhotos) t WHERE t. rownum> = @ startId AND t. rownum <= @ endId ";
// String sqlStr = "SELECT [id], [imageName], [imageUrl], [imageAlt], [notes] FROM [T_SmallPhotos] where id> 1 and id <10 ";
SqlParameter [] param = new SqlParameter [] {new SqlParameter ("@ startId", startId ),
New SqlParameter ("@ endId", endId )};
DataTable dt = sqlHelper. GetTable (sqlStr, param );
List <Photo> list = new List <Photo> ();
For (int I = 0; I <dt. Rows. Count; I ++)
{
List. add (new Photo (Convert. toInt32 (dt. rows [I] [0]), dt. rows [I] [1]. toString (), dt. rows [I] [2]. toString (), dt. rows [I] [3]. toString (), dt. rows [I] [4]. toString (), Convert. toInt32 (dt. rows [I] [5]);
}
System. Web. Script. Serialization. JavaScriptSerializer jss = new System. Web. Script. Serialization. JavaScriptSerializer (); // serialize data to json data
Context. Response. Write (jss. Serialize (list ));
}
}
Public bool IsReusable
{
Get
{
Return false;
}
}
// Encapsulate a photo class and transmit it in json format
Public class Photo
{
Public Photo (int I, string name, string url, string alt, string notes, int rownum)
{
Id = I;
ImageName = name;
ImageUrl = url;
ImageAlt = alt;
This. notes = notes;
This. rownum = rownum;
}
Private int id; // image id
Public int Id
{
Get {return id ;}
Set {id = value ;}
}
Private string imageName; // image name
Public string ImageName
{
Get {return imageName ;}
Set {imageName = value ;}
}
Private string imageUrl; // image path
Public string ImageUrl
{
Get {return imageUrl ;}
Set {imageUrl = value ;}
}
Private string imageAlt; // Image Description
Public string ImageAlt
{
Get {return imageAlt ;}
Set {imageAlt = value ;}
}
Private string notes;
Public string Notes
{
Get {return notes ;}
Set {notes = value ;}
}
Private int rownum;
Public int Rownum
{
Get {return rownum ;}
Set {rownum = value ;}
}
}
}

Among them, sqlHelper is my custom database helper class, which is relatively simple and will not be posted.
I encountered an ajax Problem in the implementation process, but I still haven't figured it out:
My js Code has two request functions: getCountPhoto () for retrieving the total number of images, and loadPhoto (startId, endId) for loading images ), when loading a page, I want to call these two functions to display the page number information and the specific image list,
Copy codeThe Code is as follows:
$ (Function (){
LoadPhoto (1, 9 );
GetCountPhoto ();
}

In this case, the page content is always incorrect. After debugging, it is found that the two ajax requests are cross-executed, not the one that completes the execution but the other.
This is what we did a few days ago.

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.