HTML and CSS Reference
In-Depth Information
function OnSuccess(results) {
alert("Converted Temperature : " + results.Value + " " + results.Unit);
}
function OnError(err) {
alert(err.status + " - " + err.statusText);
}
The Convert button's
click
event handler contains the jQuery code for invoking the
Convert()
method. The
$.ajax()
function has many configurable settings. Some common ones are used in Listing
2-14. The
url
setting allows you to specify the remote resource URL. For a WCF service, the URL takes the
form
<path_to_svc_ile>/<method_name>
.
The
type
option lets you specify the HTTP request type to be used while making the request. The
Convert()
method is configured with the
[WebInvoke]
attribute to use a
POST
method, and hence
type
is
POST
. The
data
setting indicates the data to be sent to the server (if any) while making the call. Notice how
data is captured in JSON format. A JSON object takes the form of key-value pairs: a key and its value are
separated by a colon (
:
), and multiple key-value pairs are delimited by a comma (
,
).
The
dataType
setting governs the data type of the response (XML, JSON, and so on). Recollect that the
[WebMethod]
attribute specified
ResponseFormat
as JSON, so
dataType
here must be set to JSON to correctly
process the data coming from the server.
If
Convert()
returns successfully, the function specified by the success option (
OnSuccess
) is called. If
there is any error while calling the WCF service, a function specified by the error option (
OnError
) is called.
The
OnSuccess()
function is where you process the data returned from the WCF service.
OnSuccess()
receives the return value of
Convert()
(the
TemperatureData
object) as a parameter. You can access its
Value
and
Unit
properties and display an alert box to the user.
In the
OnError()
function, you typically flag the error to the user or take some corrective action.
OnError()
receives an error object; you can display its
status
and
statusText
properties to the user.
Figure 2-10 shows a sample run of the Web Forms application.
Figure 2-10.
Sample run of Web Forms application that converts temperatures