HTML and CSS Reference
In-Depth Information
}
}
xhr.send();
}
This code declares a global
XMLHttpRequest
object so that all the other methods can use it. Inside the
jQuery
ready()
function, the
GetCustomers()
function is called.
GetCustomers()
first adds table headers
and an empty row for accepting new
Customer
details.
A new
XMLHttpRequest
object is then created. The
open()
method of the
XMLHttpRequest
object
specifies the request method as
GET
and the URL as
api/Customer
. Note that you need not specify the Web
API method name in the URL. Based on the HTTP verb (
GET
in this case), the appropriate Web API method
is automatically invoked.
You set two request headers:
Accept
and
Content-Type
. The
Accept
header is mainly for the Web API
and controls the format of the returned data (text, JSON, and so on). Because you want to access the
Customer
data items in JSON format, the
Accept
header is set to
application/json
.
The
onreadystatechange
event-handler function checks the
readyState
property of the
XMLHttpRequest
object. If
readyState
is
4
(complete), the
responseText
is parsed into a JSON object using
the
JSON.parse()
method. Recollect that the
Get()
Web API method returns an
IEnumerable
of
Customer
objects. Hence you use a
for
loop to iterate through the data object. With each iteration, a new table row is
added. Each new table row consists of text boxes filled with the existing customer information (for
example,
data[i].CustomerID
).
Next, you add the
click
event handler for the Insert, Update, and Delete buttons. Note how you use
the attribute selector to compare the value of the
<input>
elements against Insert, Update, and Delete. The
corresponding
InsertCustomer
,
UpdateCustomer
, and
DeleteCustomer
functions are wired as the event
handlers.
Once the
readystatechange
event-handler function is wired, the request is sent to the server using the
XMLHttpRequest
object's
send()
method.
The
InsertCustomer()
,
UpdateCustomer()
, and
DeleteCustomer()
functions are similar as far as their
usage of
XMLHttpRequest
is concerned.
InsertCustomer()
is shown in Listing 11-10. The other functions
follow a similar pattern.
Listing 11-10.
Inserting a New
Customer
function InsertCustomer(evt) {
var customerID = $(this).closest('tr').children().eq(0).children().eq(0).val();
var companyName = $(this).closest('tr').children().eq(1).children().eq(0).val();
var contactName = $(this).closest('tr').children().eq(2).children().eq(0).val();
var country = $(this).closest('tr').children().eq(3).children().eq(0).val();
var obj = { “CustomerID”: customerID, “CompanyName”: companyName,
“ContactName”: contactName, “Country”: country };
var xhr = new XMLHttpRequest();
xhr.open(“POST”, “api/Customer”);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
alert(“Customer Inserted!”);
GetCustomers();
}
}