Download presentation
Presentation is loading. Please wait.
Published byLaurel Norton Modified over 8 years ago
1
11 jQuery Web Service Client
2
22 Objectives You will be able to Use JSON (JavaScript Object Notation) for communcations between browser and server methods. Write JavaScript code to asynchronously invoke methods of a web service on the same server using jQuery Ajax.
3
3 JSON -- JavaScript Object Notation Generally preferred by jQuery programmers over XML. Not to mention CSV, plain text, and everything else. Represents data as a JavaScript Object Literal. Essentially just a series of name-value pairs, as quoted strings, enclosed in curly braces. { "CompanyName":"Exotic Liquids", "ContactName":"Charlotte Cooper", "Phone":"(171) 555-2222" } JSON Name Value Quotes around name are optional if name does not contain space.
4
JavaScript Testbed Download http://www.csee.usf.edu/~turnerr/Web_Application_Design/ Downloads/240_JSON/ JSON_Demo.zip http://www.csee.usf.edu/~turnerr/Web_Application_Design/ Downloads/240_JSON/ Expand Open web site in Visual Studio Set Default.html as the start page. Open Default.html Open JSON_Demo.js 4
5
Default.html 5
6
Accessing JSON Data 6 Click the Play button. A JSON object literal
7
Accessing JSON Data 7
8
More JSON Data In JSON_Demo.js window.onload = function () { var CpyName = contact.CompanyName; var CttName = contact.ContactName; var ph = contact.Phone; var card = CttName + " " + CpyName + " " + ph + " "; $('#Message').append(card); } 8
9
9 JSON Values can, themselves, be JavaScript object literals making arbitrarily complex tree structures possible. Structural recursion
10
var contacts = { "contact1": { "CompanyName": "Exotic Liquids", "ContactName": "Charlotte Cooper", "Phone": "(171) 555-2222" }, "contact2": { "CompanyName": "New Orleans Cajun Delights", "ContactName": "Shelley Burke", "Phone": "(100) 555-4822" }, "contact3": { "CompanyName": "Tokyo Traders", "ContactName": "Yoshi Nagase", "Phone": "(03) 3555-5011" } 10
11
window.onload = function () { var CpyName = contacts.contact1.CompanyName; var CttName = contacts.contact1.ContactName; var ph = contacts.contact1.Phone; var card = CttName + " " + CpyName + " " + ph + " "; var CpyName2 = contacts.contact2.CompanyName; var CttName2 = contacts.contact2.ContactName; var ph2 = contacts.contact2.Phone; var card2 = CttName2 + " " + CpyName2 + " " + ph2 + " "; var CpyName3 = contacts.contact3.CompanyName; var CttName3 = contacts.contact3.ContactName; var ph3 = contacts.contact3.Phone; var card3 = CttName3 + " " + CpyName3 + " " + ph3 + " "; var cards = card + " " + card2 + " " + card3 $('#Message').append(cards); } 11
12
Looping Over an Object's Members jQuery provides a function that lets us loop through all of the items of a JSON object. $.each(JSON, function(name, value) Pass $.each a JSON object and a function. The function will receive the name and value of each item of the object. 12
13
In JSON_Demo.js Replace window.onload with: window.onload = function () { $.each(contacts, function(contact, contactInfo) { var CpyName = contactInfo.CompanyName; var CttName = contactInfo.ContactName; var ph = contactInfo.Phone; var card = CttName + " " + CpyName + " " + ph + " "; $('#Message').append(card + " "); }) } 13
14
Same Result 14
15
JSON Arrays A JSON value can be an array. JSON arrays are written inside square brackets. Each element is a JSON object literal. Elements are separated by commas. Example: "employees": [ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter","lastName":"Jones"} ] http://www.w3schools.com/json/json_syntax.asp 15
16
var contacts = { "contactArray": [ { "CompanyName": "Exotic Liquids", "ContactName": "Charlotte Cooper", "Phone": "(171) 555-2222" }, { "CompanyName": "New Orleans Cajun Delights", "ContactName": "Shelley Burke", "Phone": "(100) 555-4822" }, { "CompanyName": "Tokyo Traders", "ContactName": "Yoshi Nagase", "Phone": "(03) 3555-5011" } ] } 16
17
Processing Array Elements window.onload = function () { for (i = 0; i < 3; i++) { var CpyName = contacts.contactArray[i]["CompanyName"]; var CttName = contacts.contactArray[i]["ContactName"]; var ph = contacts.contactArray[i]["Phone"]; var card = CttName + " " + CpyName + " " + ph + " "; $('#Message').append(card + " "); } 17 Note different way of identifying the name.
18
Same Result 18
19
19 A JSON Object Literal is NOT a String. // A JavaScript object literal var obj = { "Name": "John" }; alert(obj); alert(obj.Name); // A string var obj = '{ "Name":"John" }'; alert(obj);
20
20 jQuery.parseJSON() Converts a string representing a JSON object into an actual JavaScript JSON object. // A string var obj = '{"Name":"John" }'; // A JSON object var obj2 = jQuery.parseJSON(obj); alert(obj2.Name); parseJSON requires double quotes around names and values in the string to be parsed. as shown above. http://api.jquery.com/jquery.parsejson/ End of Section
21
Web Services Web Service A software function provided at a network address over the Web. Designed to support machine-to-machine interaction. http://en.wikipedia.org/wiki/Web_service 21
22
Web Services SOAP Based Services http://www.w3.org/TR/soap/ Windows Communication Foundation http://msdn.microsoft.com/en-us/library/ms731082%28v=vs.110%29.aspx RESTful Services Representational State Transfer (Roy Fielding, 2000) http://msdn.microsoft.com/en-us/magazine/dd315413.aspx ASP.NET Web Services (.asmx services) Originally SOAP based We will invoke with jQuery Ajax Example on following slides 22
23
23 A Simple Web Service and Client Let’s rewrite the Server_Calculation example from last class as a web service. Just code to run on the web server. No associated HTML page. Then write a jQuery Ajax based client. Use JSON for communication. Download Server_Calculation example from last class: http://www.csee.usf.edu/~turnerr/Web_Application_Design/ Downloads/2016_04_07_Ajax/ http://www.csee.usf.edu/~turnerr/Web_Application_Design/ Downloads/2016_04_07_Ajax/ Ajax_jQuery_Demo.zip
24
24 Ajax_jQuery_Demo Review example from last class Default.html - Set as Start Page Ajax_jQuery_Demo.js Requests a page, using jQuery Ajax server_calculation.aspx.cs Gets inputs from query string Parses strings as Decimal Computes sum Returns sum as string
25
25 A Simple Web Service and Client Create a new ASP.NET Empty Web Site. Web_Service_Demo Website > Add New Item JavaScript File Web_Service_Client.js Website > Add Existing Item jquery-2.2.2.min.js (from download) Default.html (from download) Update src of second script in Default.html to Web_Service_Client.js
26
Default.html 26
27
27 Website > Add New Item
28
28 Computation_Service.asmx
29
29 App_Code/Computation_Service.cs Set Namespace to your own URL. Not used as a URL. Just a way to create globally unique name Uncomment the attribute: [System.Web.Script.Services.ScriptService] Replace web method HelloWorld with Compute_Sum, as shown on the next slide.
30
Computation_Service.cs using System; using System.Web.Services; [WebService(Namespace = "http://rollinsturner.net/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.Web.Script.Services.ScriptService] public class Computation_Service : System.Web.Services.WebService { public Computation_Service(){ } [WebMethod] public string compute_Sum(Decimal input1, Decimal input2) { Decimal sum = input1 + input2; String result = "{\"Sum\": \"" + sum.ToString() + "\" }"; return result; } 30 String representation of a JSON object
31
Test the Web Service In Solution Explorer, select Computation_Service.asmx Click the Play button Or press F5 31
32
Computation_Service in the Browser 32 Click this link to test the web service.
33
Provide Test Inputs 33 Click here
34
Result 34
35
35 Web_Service_Client.js Bind event handler to button click event. $(document).ready(function () { $('#btnComputeSum').bind('click', Get_Sum); }); Unobtrusive JavaScript Same as writing onclick="Get_Sum();" in the HTML tag.
36
Start with a Stub 36
37
Testing with the Stub 37
38
38 The jQuery ajax Method Use the jQuery ajax method to invoke the web service. $.ajax( ) No parameter for $ ajax parameter will be a JavaScript Object Literal Series of name-value pairs Shown on next slide http://api.jquery.com/jQuery.ajax/
39
39 Web_Service_Client.js function Get_Sum(evt) { evt.preventDefault(); var t1= $('#Text1').val(); var t2= $('#Text2').val(); var params = '{ "input1": "' + t1 + '", ' + ' "input2": "' + t2 + '" } '; $.ajax({ type: "POST", dataType: "json", data: params, contentType: "application/json; charset=utf-8", url: "Computation_Service.asmx/Compute_Sum", success: Process_Result, error: Process_Error }); } String representation of a JSON object
40
40 Processing the Result In the callback function, Process_Result We will get a JavaScript JSON Object. In the normal case its “d” property is our result. String representation of a JSON object Example: {"sum":"3.3333"} In the error case, its “responseJSON” property has information about the error. responseJSON.Message is an error message.
41
41 Callback Functions function Process_Result(response) { var result = response.d; var obj = jQuery.parseJSON(result); var sum = obj.Sum; $('#Message').text(sum); } function Process_Error(response) { $('#Message').text(response.responseJSON.Message); } Add to Web_Service_Client.js
42
42 jQuery_Web_Service_Client in Action
43
Error Case 43
44
44 References We have used the following jQuery methods: ajax http://api.jquery.com/jQuery.ajax/ each http://api.jquery.com/each/ find http://api.jquery.com/find/ preventDefault http://api.jquery.com/event.preventDefault/
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.