Ajax HACKS-HACK6 receive digital data

Source: Internet
Author: User
Tags format object button type exception handling object model string variable tostring
ajax| data Ajax hacks-hack6 receive digital data

This hack receives the stock price in digital form and then displays the result after the user input processing. If the server does not return the correct number, the program displays an error message.

A great step forward in Ajax technology is to receive discontinuous data from the server, rather than the entire page. Sometimes, these discontinuous messages have to be a number, not as a string (as the previous hack said) or other objects. JavaScript can easily convert other kinds of data into numbers without user intervention, but still, users don't want to get some strange data from the server (requiring format checking).

This hack checks the user-entered "Stock Number" format in a correct number format. The price of the stock is then received from the server. The results of the processing are then dynamically displayed.

Figure 1-6 Browser display diagram

Figure 1-6. Show Total

Here is the HTML code for the page:


"Http://www.w3.org/tr/1999/rec-html401–19991224/strict.dtd" >

Your Total-Stock Holdings

Javascript:void%200>
"Getstockprice (This.stsymbol.value,this.numshares.value); return false" >

Enter stock symbol:



Enter Share amount:



Get Total Value

When the user clicks the Get Total Value button, the action leads to the presentation event of the single element. The Getstockprice function is used to handle events. Function gets the stock symbol and the number of shares as an argument. The return false part of the Event-handling code cancels the browser's typical submission of the form values to the URL SP Ecified by the form tag ' s action attribute.

The following is the code for the Hack4.js file:

var request;

var symbol; Save Stock Code

var numberofshares;

function Getstockprice (SYM,SHS) {

if (sym && SHS) {

Symbol=sym;

NUMBEROFSHARES=SHS;

var url= "http://www.parkerriver.com/s/stocks?symbol=" +SYM;

HttpRequest ("Get", url,true);

}

}

Event handler for XMLHttpRequest

function Handleresponse () {

if (request.readystate = = 4) {

alert (request.status);

if (Request.status = = 200) {

/* Check If the return value is actually a number.

If So, multiple by the number of shares and display the result * *

var stockprice = Request.responsetext;

try{

if (isNaN (StockPrice)) {throw new Error (

"The returned price are an invalid number.";}

if (isNaN (numberofshares)) {throw new Error (

"The share amount is a invalid number.";}

var info = "Total stock value:" + calctotal (StockPrice);

Displaymsg (document.

getElementById ("Msgdisplay", info, "BLACK";

document.getElementById ("Stprice". style.fontsize= "0.9em";

document.getElementById ("Stprice". InnerHTML = "Price:

"+stockprice;

} catch (Err) {

Displaymsg (document.getElementById ("Msgdisplay"),

"An error occurred:" +

Err.message, "Red";

}

} else {

Alert

"A problem occurred with communicating between" +

"XMLHttpRequest object and the server program.";

}

}//end outer IF

}

/* HttpRequest () and

Initreq () function See HACK1 and 2 * *

function Calctotal (price) {

Return Stripextranumbers (Numberofshares * price);

}

/* Strip any characters beyond a scale of four characters

Past the decimal point, as in 12.3454678 * *

function stripextranumbers (num) {

Check if the number ' s already okay

Assume a whole number is valid

var N2 = num.tostring ();

if (N2.indexof ("." = = 1) {return num;}

If it has numbers after the decimal point,

Limit the number of digits after the decimal point to 4

We use parsefloat if strings are passed to the method

if (typeof num = "string" {

num = parsefloat (num). toFixed (4);

} else {

num = num.tofixed (4);

}

Strip any extra zeros

Return parsefloat (Num.tostring (). Replace (/0*$/, "");

}

function Displaymsg (div,bdytext,txtcolor) {

Reset DIV Content

Div.innerhtml= "";

Div.style.backgroundcolor= "Yellow";

Div.style.color=txtcolor;

Div.innerhtml=bdytext;

}

Data processing begins with Handleresponse (). First the code receives a string, passing the variable var stockprice = Request.responsetext. Then the variable stockprice format is checked, using the JS function isNaN (). JS in the use of this function for the relevant check is very common. For example: isNaN ("Goodbye") returns True because "Goodbye" cannot be converted to numbers. The code also checks the format of the number of shares entered by the user.

If a function returns True, indicating that there is an invalid input value, the code throws an exception. This is like saying: You cannot process these values, modify them. The page then displays an error to the user.

Exception handling See HACK8

The Calctotal () function multiplied two values to display the results to the user.

Using the Document Object model, you can dynamically display the results without refreshing the page.

Displaymsg (document.getElementById ("Msgdisplay"), info, "Black");

document.getElementById ("Stprice". style.fontsize= "0.9em";

document.getElementById ("Stprice". InnerHTML = "Price:" +stockprice;

The Displaymsg () function is also simple. It has a parameter that represents of the font color, which allows the code to set the font color "red" for error messages:

function Displaymsg (div,bdytext,txtcolor) {

Reset DIV Content

Div.innerhtml= "";

Div.style.backgroundcolor= "Yellow";

Div.style.color=txtcolor;

Div.innerhtml=bdytext;

}

Figure 1-7 shows what the page looks as the user requests a stock value.

Figure 1-7. Tallying your investment

Figure 1-8 shows a example error message, in case the user enters values that cannot is used as numbers or the server ret Urns invalid values.

Figure 1-8. Has a bad number day

<

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.