Real-time display of shares in Ajax instances

Source: Internet
Author: User
Tags netbeans
Instance content

The specific content of the instance is: the server generates the stock price at a specified time, calculates the increase, and sends it to the client page in JSON format. The client page obtains the server data at a specified time, parse the JSON data format and display the daily limit.

The example is from Wang xingkui's Ajax teaching video. The video is written in the Java language of the netbeans environment. It is not difficult to compile the tutorial by using netbeans, so I want to write it in the C # environment of vs2010. The Code is as follows.

Instance code stocks. CS

Stock. CS, stock class code:

/// <Summary> /// Stock Information Class /// </Summary> public class stock {public stock (string ID, string name, double yesterday) {This. SID = ID; this. name = Name; this. yesterday = yesterday; this. today =-1; this. highest = yesterday; this. current = yesterday; this. lowest = yesterday;} // stock ID private string Sid; // stock name private string name; // Yesterday's stock price private double yesterday; // Today's stock price private double today; // maximum private double highest; // minimum private double lowest; // The current stock price is private double current; // floating private string range; /// <summary> /// obtain the current stock price /// </Summary> /// <returns> </returns> Public double getcurrent () {Return Current ;} /// <summary> /// get yesterday's stock price /// </Summary> /// <returns> </returns> Public double getyesterday () {return yesterday ;} /// <summary> /// get today's stock price /// </Summary> /// <returns> </returns> Public double gettoday () {return today ;} /// <summary> /// obtain the highest stock price /// </Summary> /// <returns> </returns> Public double gethighest () {return highest ;} /// <summary> /// get the lowest share price /// </Summary> /// <returns> </returns> Public double getlowest () {return lowest ;} /// <summary> /// get the floating value /// </Summary> /// <returns> </returns> Public String getrange () {return range ;} public void setrange (string range) {This. range = range ;} /// <summary> /// set the current stock price /// </Summary> /// <Param name = "current"> current stock index </param> Public void setcurrent (double current) {// calculate the increment Double range = (current-this. yesterday)/This. yesterday; // if the increase exceeds 10% if (range> 0.1) {current = math. round (1.1 * This. yesterday * 100)/100.0;} // If the decline exceeds 10% if (range <-0.1) {current = math. round (0.9 * This. yesterday * 100)/100.0;} This. current = current; // If (this. today =-1) {This. today = current;} // set today's stock price if (this. current> This. highest) {This. highest = This. current;} else if (this. current <this. lowest) {This. lowest = This. current;} // This. range = range. tostring ("p ");}}
XMLHTTP. js

XMLHTTP. JS is a custom myxmlhttprequest "class, mainly responsible for interaction with the server:

// The people who use the encapsulation method only care about the HTTP request method, URL address, Data, successful and failed callback method. // the construction method of the class, the primary responsibility is to create the XMLHTTPRequest object var myxmlhttprequest = function () {var XMLHttpRequest; If (window. XMLHttpRequest) {XMLHttpRequest = new XMLHttpRequest (); If (XMLHttpRequest. overrideminetype) {XMLHttpRequest. overrideminetype ("text/XML") ;}} else if (window. activexobject) {var activename = ["xsxml2.xmlhttp", "Microsoft. XMLHTTP "]; for (I = 0; I <activename. le Ngth; I ++) {try {XMLHttpRequest = new activexobject (activename [I]); break;} catch (E) {}}} if (XMLHttpRequest = undefined | XMLHttpRequest = NULL) {alert ("XMLHTTPRequest object creation failed! ");} Else {This. XMLHTTP = XMLHttpRequest; }}// the method by which the user sends the request. myxmlhttprequest. prototype. send = function (method, URL, Data, callback, failback) {If (this. XMLHTTP! = Undefined | this. XMLHTTP! = NULL) {method = method. touppercase (); If (method! = "Get" & method! = "Post") {alert ("the HTTP request method must be get or post"); return;} If (url = undefined | url = NULL) {alert ("http request address must be set"); return;} var tempxmlhttp = This. XMLHTTP; tempxmlhttp. onreadystatechange = function () {If (tempxmlhttp. readystate = 4) {If (tempxmlhttp. status = 200) {var responsetext = tempxmlhttp. responsetext; var responsexml = tempxmlhttp. responsexml; If (callback = undefined | callback = nu Ll) {alert ("No method for correctly returning data for processing"); alert ("returned data:" + responsetext);} else {callback (responsetext, responsexml );}} else {If (failback = undefined | failback = NULL) {alert ("no processing method for failed data processing"); alert ("HTTP response code information: "+ tempxmlhttp. status + ", response code text:" + tempxmlhttp. statustext) return;} else {failback (tempxmlhttp. status, tempxmlhttp. statustext) ;}}}// solves the cache conversion if (URL. indexof ("? ")> = 0) {url = URL +" & t = "+ (new date (). valueof () ;}else {url = URL + "? T = "+ (new date ()). valueof ();} // solves the cross-origin problem if (URL. indexof ("http: //")> = 0) {URL. replace ("? "," & "); Url = URL +" Proxy? Url = ";} This. XMLHTTP. open (method, URL, true); // if it is post, you need to set the request header if (Method = "Post") {This. XMLHTTP. setRequestHeader ("Content-Type", "application/X-WWW-form-urlencoded");} This. XMLHTTP. send (data);} else {alert ("XMLHTTPRequest object creation failed, unable to send data. ") ;}} myxmlhttprequest. prototype. abort = function () {This. XMLHTTP. abort ();}

Handler. aspx

Generally, handler. ashx is used to process client requests:

<% @ Webhandler Language = "C #" class = "handler" %> using system; using system. collections. generic; using system. LINQ; using system. web; using system. web. ui; using system. web. UI. webcontrols; using system. threading; // namespace of stringbuilder using system. text; public class handler: ihttphandler {// defines the stock dictionary private dictionary <string, stock> stock; private system. timers. timer timer; /// <summary> /// respond to client requests /// </Summary> /// <Param name = "context"> Request Information </param> Public void processrequest (httpcontext context) {context. response. contenttype = "text/html; charset = UTF-8"; // response. contenttype = "text/html; charset = UTF-8"; // initialize the data Init (); // convert to a JSON string thread. sleep (1, 200); stringbuilder builder = new stringbuilder (); builder. append ("({"); // stockid array string [] stockid = new string [stock. count]; // obtain the stock ID for (INT I = 0; I <stock. count; I ++) {stockid [I] = stock. elementat (I ). key. tostring () ;}// obtain the stock according to the stock ID and splice the string for (INT I = 0; I <stock. count; I ++) {string SID = stockid [I]; stock tempstock = stock [Sid]; builder. append (SID ). append (": {yes :"). append (tempstock. getyesterday ()). append (", Todd :"). append (tempstock. gettoday ()). append (", high :"). append (tempstock. gethighest ()). append (", low :"). append (tempstock. getlowest ()). append (", cur :"). append (tempstock. getcurrent ()). append (", ran :'"). append (tempstock. getrange ()). append ("'}"); // Add "," if (I <stock. count) {builder. append (",") ;}// Add at the end}) builder. append ("})"); // The response context. response. write (builder);} // <summary> // initialize the configuration data // </Summary> private void Init () {// create four new stocks: stock szzs = new stock ("300001", "Shanghai Stock Index", 300); stock pfyh = new stock ("600000", "Shanghai Pudong Development Bank ", 25); stock gsyh = new stock ("601398", "ICBC", 6.5); stock zgsy = new stock ("601857", "CNPC", 19.1 ); // set the stock dictionary stock = new dictionary <string, stock> (); // Add the stock Stock. add ("300001", szzs); stock. add ("600000", pfyh); stock. add ("601398", gsyh); stock. add ("601857", zgsy); // set the timer parameter, not too large timer = new system. timers. timer (50); timer. enabled = true; // execute the timer function theout random RDM = new random. nextdouble (); // The timer oscillating event. The timer is executed using an anonymous function. elapsed + = delegate (Object source, system. timers. elapsedeventargs e) {// stock change range // floating up double SZ = MCM * 30; double pF = MCM * 0.5; double GS = MCM * 0.1; double zg = MCM * 0.3; // down floating if (MCM> 0.5) {SZ = 0-SZ;} If (MCM> 0.5) {pF = 0-PF ;} if (MCM> 0.5) {GS = 0-GS;} If (MCM> 0.5) {zg = 0-ZG;} // current stock price szzs. setcurrent (math. round (szzs. getcurrent () + sz) * 100)/100.0); pfyh. setcurrent (math. round (pfyh. getcurrent () + PF) * 100)/100.0); gsyh. setcurrent (math. round (gsyh. getcurrent () + GS) * 100)/100.0); zgsy. setcurrent (math. round (zgsy. getcurrent () + zg) * 100)/100.0 );};} /// <summary> /// implement the built-in functions of the interface /// </Summary> Public bool isreusable {get {return false ;}}}
Refresh.html

Refresh.html, used to send a request to update the stock information:

<! 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"> Running result

Download and preview

This is because the Java language in the netbeans environment is converted to the C # language in vs2010, and many problems are encountered in the middle. These problems will be introduced in the next blog, and the code of this instance is attached: http://download.csdn.net/detail/lidaasky.

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.