Ajax HACKS-HACK8 processing Request Object Errors

Source: Internet
Author: User
Tags object bool button type exception handling connect response code try catch window
Ajax|object|request| Error Ajax hacks-hack8 processing request Object Errors

Allow Ajax to detect server errors and provide useful information to users.

The beauty of Ajax technology is that it allows JavaScript to connect to the server without user intervention. JavaScript developers, however, often have no control over the server component (possibly a Web service or other software). Even though your application includes your own server components, you cannot guarantee that the server is always running properly or that the user has encountered an error. Therefore, when the program error, we must ensure that the application of industrial procedures can be restored.

This hack traces the error and displays an error message when the AJAX program loses the server connection.

Problem, problem ...

Hack captures the following exception events and recommends solutions for the application:

The Web application or server component you are connecting to is temporarily unavailable.

The server on which the application is connected has been hung, or the URL has changed.

The server component that you want to connect to is wrong and has an attack during the connection.

When the Requst object calls the Open method, the code uses a different host address than the Web page address that the user downloaded. When the open method is called, the Request object throws an exception.

You can use the exception handling method of this hack in other places. Hack also uses HACK6 's stock-calculation program code. Take a look at the HTML code:

"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 users load this file into their browsers, they to the screen shown in Figure 1-11.

Figure 1-11. Request a stock ' s price

The code we are interested in is the part that catches the exception, the backend server shuts down, the error, or the wrong URL. The Handleresponse function is the event handler function used to manage the server response, Request.onreadystatechange=handleresponse. The next code uses try/catch/finally to catch and handle the problem of invalid numbers.

function Handleresponse () {

var statusmsg= "";

try{

if (request.readystate = = 4) {

if (Request.status = = 200) {

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

If So, multiple by the number

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 {

Request.status is 503 if the application isn ' t available;

If the application has a bug

Alert

"A problem occurred with communicating between"

"XMLHttpRequest object and the server program." +

"Please try again very soon";

}

}//end outer IF

} catch (Err) {

Alert ("It does not appear that server" +

' is available to this application. Please "+

"Try again very soon." \\nError: "+err.message);

}

}

Here's a look at the code to handle different exceptions.

The try block throws any internal exception, and the corresponding catch catches the exception and resolves the exception. Try catch is relative.

What happens when the mainframe hangs off? Although the URL you requested is correct. In this case, the code that attempts to access the Request.status property throws an exception, and the request object should not receive a response from the server, and the corresponding state attribute.

Therefore, the code will pop up a warning dialog box to prompt the user.

Figure 1–12 depicts what the alert window looks like after this type of error.

Figure 1-12. Uh-oh, server down

The code shows the user's information, as well as more information about the exception error. You can learn some information, but these are helpful for modifying and debugging the program.

The error variable in the code is a JavaScript error object. The information property of an object is an error message, a string generated by the JavaScript engine.

If the try/catch/finally mechanism is not used, the user can only see error messages that are not easily understood by the JavaScript engine. After closing this annoying error box, users will not be able to understand the application's more state information.

Sometimes the server or host is functioning correctly, but there is a problem with the server components to which you are connecting. In this case, the value of the Request.status property is 503 (the service is not available). Because the value of the State property is not 200, this part of the code will catch this exception:

} else {

Request.status is 503 if the application isn ' t available;

500 If the service has errors

Alert

"A problem occurred with communicating between"

"XMLHttpRequest object and the server program." +

"Please try again very soon";

}

In other words, users can see application state information in a pop-up window. You can also display errors for server components. In this case, the response status code is 500 (internal service error). Additionally, the 404 Status Response code indicates that the server's static or dynamic component cannot find the requested URL, which is a common annoying 400 error (the page does not exist or is deleted).

The try/catch/finally statement applies only to versions 1.4 or higher. The finally statement is optional.

Frustrating URL of the wrong

What happens if a user requests a URL that is wrong or has changed? Calling the Request.open method throws an exception and must be handled inside the try/catch/finally statement.

In the criminal initreq (), there is the corresponding code:

function HttpRequest (reqtype,url,asynch) {

mozilla-based Browsers

if (window. XMLHttpRequest) {

Request = new XMLHttpRequest ();

else if (window. ActiveXObject) {

Request=new ActiveXObject ("msxml2.xmlhttp");

if (! Request) {

Request=new ActiveXObject ("Microsoft.XMLHTTP");

}

}

The request could still be null if neither ActiveXObject

Initialization succeeded

if (request) {

Initreq (Reqtype,url,asynch);

} else {

Alert ("Your browser does not permit the use of" +

"Of this application ' s features!";

}

}

/* Initialize A Request object is already constructed * *

function Initreq (reqtype,url,bool) {

try{

/* Specify the function that would handle the HTTP response * *

Request.onreadystatechange=handleresponse;

Request.open (Reqtype,url,bool);

Request.send (NULL);

} catch (Err) {

Alert

"The application cannot contacts the server at the moment." +

"Please try again in a few seconds."

}

}

The other scenario is that the requested URL is not what you want. For example, the user wants to download the page from Http://www.myorg.com/app, but the open URL is http://www.myorg.com, and such an error can be captured using the try/catch/finally statement.

This hack describes the common exceptions to Ajax and how to capture them.

<

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.