Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

380 CHAPTER 8 Websites and services


function serverDivision(data) {
return $.ajax({
url: '/divide',
data: data,
type: 'DELETE',
dataType: 'json',
cache: false
});
}
If you display the webpage and enter numbers for x and y, you should see proper return
values until you try to divide by zero. In JavaScript, dividing by zero doesn’t throw an excep-
tion; it returns infinity. The conversion to a JSON object will, however, throw a parse error, so
no value is displayed.
To solve this problem, a displayError function is added, and the promise’s fail method is
used to subscribe to the failure of the AJAX call, as shown in the following code example.
function divideNumbers() {
var data = getFormData();
serverDivision(data).done(displayResult).fail(displayError);
}

function displayError(serverData, error) {
var value = 'No result';
if ('result' in serverData) value = serverData.result;
$('#result').html(value + ' - ' + error);
}
The fail method is chained to the serverDivision call after the done method call. In addi-
tion, the displayError function determines whether serverData has a result property by using
the in keyword. If the result property exists, its value will be displayed. This function has a
second parameter, called error, that identifies the source of the error. Both of these items are
concatenated and displayed.

Cross-origin resource sharing


In the previous examples, the Math.html webpage came from the same website that con-
tained the web service, and the URL for the web service requests was a relative URL on the
site. If the Math.html page had AJAX called, and it contained URLs to access web services on
other websites, the AJAX call would fail because this represents a potential cross-site script-
ing (XSS) attack. There are ways to allow cross-site AJAX calls, the most common of which is
cross-origin resource sharing (CORS). CORS is a browser specification that defines ways for a
web server to allow its resources to be accessed by a webpage from a different domain. CORS
provides a compromise by which you can configure access across domains instead of allowing
everyone access or denying everyone access.
You implement CORS on the web server by sending the Access-Control-Allow-Origin
header when the web service is accessed. Here is an example of the header.
Access-Control-Allow-Origin: *

Key
Te rms
Free download pdf