Upload
dominion
View
3.893
Download
4
Tags:
Embed Size (px)
DESCRIPTION
Introduction to JSON What it is Why you should care Enough to make you (a little) dangerous Introduction to AJAX What is AJAX? How can it be used in Domino apps? How to make an AJAX request Using JSON as the AJAX data format (instead of XML) Putting it into an application
Citation preview
®
JSON and AJAX JumpStartScott Good, PresidentTeamwork SolutionsColumbus / Cincinnati
Scott Good
President, Teamwork SolutionsColumbus, Cincinnati2-time Beacon Award Finalists
Notes Developer/Designer, 15 years
Extensive workflow and web development experienceProcessIt! (2003 E-Pro Apex Award, 2006 & 2007 Advisor Editors’ Choice Award winner)
Have written nearly 50 Lotus Advisor articlesAJAXCSSJavaScriptLotusScriptDomino web development
Teamwork Solutions…
Does application development for companies of all sizesAbbott LaboratoriesAbercrombie & FitchAmerican Cancer SocietyAmerican Electric PowerBurger KingNationwide InsurancePharmacia UpjohnPrudential InsuranceAnd many more
Today…
Introduction to JSONWhat it isWhy you should careEnough to make you (a little) dangerous
Introduction to AJAXWhat is AJAX?How can it be used in Domino apps?How to make an AJAX requestUsing JSON as the AJAX data format (instead of XML)Putting it into an application
JSON and AJAX…makes you think…
Wrong JSON
It’s “JSON,” the web technology, not “Jason” the homicidal maniacImportant safety tip
So, what is JSON?
JSON = JavaScript Object Notation
A part of JavaScript many developers don’t know aboutHas been a part of the JavaScript spec since December 1999
Extends the power of JavaScript arrays
Can act as a viable (and much easier to use) alternative to XML as a data transport
JavaScript Variables
In JavaScript, variables can contain more or less anythingNumbersTextArraysFunctionsObjects…in any combination
You can, for instance, do this:
var myChild = “Sydney”;var age = 14;var gender = “female”;
Or, you could use an array
JavaScript variables don’t have to be single valuesThey can contain arrays
Array elements are identified by position number, starting with zero
var myChild = [“Sydney”, 14, “female”];
… so that …
var sydneyAge = myChild[1];
Works great…but hard to keep track of what is whereAnd hard to read the code
JavaScript Arrays
Array elements can also be identified by name
var myChild = []; // identifies myChild as an array
myChild[“name”] = “Sydney”;
myChild[“age”] = 14;
myChild[“gender”] = “female”;
… so that …
var sydneyAge = myChild.age;
Easier to read as code; not much easier to create
JavaScript Arrays
Named array elements can also be identified in a single statement:
var myChild = {name: “Sydney”, age: 14, gender: “female”};
… or, spread out for better readability …
var myChild = {
name: “Sydney”,
age: 14,
gender: “female”
};
Note the braces
JavaScript Arrays
Functionally, these are the same:
var myChild = []; myChild[“name”] = “Sydney”;myChild[“age”] = 14;myChild[“gender”] = “female”;
… is the same as …
var myChild = {name: “Sydney”, age: 14, gender: “female”
};
JSON
But THIS one is considered JSON:
var myChild = {name: “Sydney”, age: 14, gender: “female”
};
Easier to write; easier to read; (better on the resume)
But, if that was all there was to it, nobody would careFortunately, that’s not all there is to it
JSON = JavaScript Object Notation
JSON is a extension of JavaScript capabilities
JSON is a means of describing JavaScript objects which can be filled with pretty much anything JavaScript
As the object model gets more complex, defining the data can getmore complicated, too
JSON can help simplify access to the data
Basic JSON Format
Simple format: An overall object name, then pairs of names and values inside braces…
var objectName = {
identifier1: value1,
identifier2: value2,
identifier3: value3
}
Keep in mind, this is JavaScript“values” can be pretty much anything, not just simple things like strings
Basic JSON Format
You will often see the identifiers in quotation marks, too…
var objectName = {
“identifier1”: value1,
“identifier2”: value2,
“identifier3”: value3
}
In my experience, it works either way
Note where the commas are!
Why bother?...A bit bigger example
Imagine you have an array of objects you need to track…
var myKids = [“Corey”, “Thaddeus”, “Sydney”, “Cameron”];
Simple enough…you don’t need JSON for that
So, why do this?
But what if there’s other, related, information you want to track?
var myKids = [“Corey”, “Thaddeus”, “Sydney”, “Cameron”];
var kidsAges = [21, 21, 14, 7];
var kidsGender = [“female”, “male”, “female”, “female”];
The data model is starting to get more complex
Relationships between data are based entirely on array position
Extracting data gets harder
Find Sydney’s age…
var myKids = [“Corey”, “Thaddeus”, “Sydney”, “Cameron”];var kidsAges = [21, 21, 14, 7];var kidsGender = [“female”, “male”, “female”, “female”];for (var x = 0; x < myKids.length; x++){
if (myKids[x] == “Sydney”){var sydneyAge = kidsAges[x];break;
}}
Quite do-able, but fussy…and surprisingly hard for what it is
With JSON, the data model is simpler
One set of named-pairs can contain others:
var myKids = {Corey: {
age: 21, gender: “female”
},Thaddeus: {age: 21, gender: “male”},Sydney: {age: 14, gender: “female”},Cameron:{ age: 7, gender: “female”}
};
var sydneyAge = myKids.Sydney.age;
Easier to get right, and to read
Which are you more likely to get right when building the arrays?
var myKids = [“Corey”, “Thaddeus”, “Sydney”, “Cameron”];var kidsAges = [21, 21, 14, 7];var kidsGender = [“female”, “male”, “female”, “female”];
… or …
var myKids = {Corey: {age: 21, gender: “female”},Thaddeus: {age: 21, gender: “male”},Sydney: {age: 14, gender: “female”},Cameron:{ age: 7, gender: “female”}
};
Easily extend the data model
You can easily add more named-pair sets…
var myKidsAndPets = {kids: {
Corey: {age: 21, gender: “female”},Thaddeus: {age: 21, gender: “male”},Sydney: {age: 14, gender: “female”},Cameron:{ age: 7, gender: “female”}
},pets: {
Kirby: {type: “dog”, variety: “Labrador Retriever”},Spot: {type: “fish”, variety: “Goldfish”}
}};
var sydneyAge = myKidsAndPets.kids.Sydney.age;
Again, consider the alternative…
MUCH harder to see relationships the “traditional” way…
var myKids = [“Corey”, “Thaddeus”, “Sydney”, “Cameron”];var kidsAges = [21, 21, 14, 7];var kidsGender = [“female”, “male”, “female”, “female”];var ourPets = [“Kirby”, “Spot”];var petTypes = [“dog”, “fish”];var petVarieties = [“Labrador Retriever”, “Goldfish”];
And, it gets worse if the sequence of variable declarations isn’t in a totally logical order
JSON: Who Cares?
You do (or should), particularly if you’re doing things with relatively complex data in JavaScript
Or, if you’re using AJAX
In AJAX, JSON is an easier approach to doing what you’re probably already doing with XML
MUCH easier
JSON vs XML…why bother with XML?
var myKidsAndPets = {kids: {
Corey: {age: 21, gender: “female”},Thaddeus: {age: 21, gender: “male”},Sydney: {age: 14, gender: “female”},Cameron:{ age: 7, gender: “female”}
},pets: {
Kirby: {type: “dog”, variety: “Labrador Retriever”},Spot: {type: “fish”, variety: “Goldfish”}
}};
JSON is about half the characters (in this example), but you also have to parse the XML before you can use it
<myKidsAndPets><children>
<child><name>Corey</name><age>21</age><gender>female</gender>
</child><child>
<name>Thaddeus</name><age>21</age><gender>male</gender>
</child><child>
<name>Sydney</name><age>14</age><gender>female</gender>
</child><child>
<name>Cameron</name><age>7</age><gender>female</gender>
</child></children><pets>
<pet><name>Kirby</name><type>dog</type><variety>Labrador Retriever</variety>
</pet><pet><name>Spot</name>
<type>fish</type><variety>Goldfish</variety>
</pet></pets>
</myKidsAndPets>
XML vs JSON…mostly the same
There are some data formats supported by XML not supported by JSON (audio, video)
Unimportant for most of what we do
JSON is much easier to work withEasier to buildEasier to readEasier to parseLess data = faster to transportAnd, hey!, less typing
JSON is a Good Thing…particularly with AJAX
So, how do you use JSON in web apps?
In JS Header
In JavaScript libraries
Computed into on-the-form JavaScript variablesUsing @DbLookup or WebQueryOpen agents
Or, from Notes Views, along with AJAX…
JSON is now available from Domino views
Beginning with Domino 7.0.2, you can get JSON from web views
…/ViewName?ReadViewEntries&OutputFormat=JSON
Formatting/node names are a LOT like the XML version
Demos
JSON from a JS Library
JSON from the JS Header
JSON from ComputedText
XML vs JSON from Notes web viewsCompare the node names, structure
BUT…can’t actually get directly to it
Views return JSON objects, but what are you going to do with them?
Can only get the JSON code with a URLNOT as a DbLookup or an embedded view
CAN use the Notes View JSON in an AJAX call…
What is AJAX?
Asynchronous JavaScript And XMLEr…or JSON…or other stuff…
VERY hot right now (but not new)
A combination of technologies that have literally transformed web applications over the last few years
Able to work independently of the UIThat’s the “Asynchronous” part
Can use XML as the data transport, but doesn’t have toCan be JSONOr even plain text
Why should you care?
Can make web applications much…FasterMore intuitiveEasier to use
Breaks through a lot of traditional limitations of web applications
Creates a sometimes-link with the server without requiring the UI to refresh
Demo Google Maps
How can it be used in Domino apps?
Lets you dynamically retrieve data from the server while the user does something else
Possible uses:Check budget availabilityValidate part numbersGet sub-category lists from top-category choiceLook up names from NAB as characters are typed
The list is limited mostly by your imagination
NOTE: Older browsers cannot do this (IE prior to 5.5 or so, etc)
How to make an AJAX request
The basic object, which makes the request, varies depending on browser
MS Internet Explorer (before IE 7.0)Uses XMLHTTP ActiveX objectajaxReq = new ActiveXObject(“Microsoft.XMLHTTP”);
Firefox, IE 7.0, etc.Use an internal XMLHttpRequest objectajaxReq = new XMLHttpRequest();
How to make an AJAX request
Unless you can be absolutely sure of the browser, you just build for both and be done with it
Determine which is supported by the browser by checking for window.ActiveXObject and/or window.XMLHTTPRequest
Building an AJAX request
function createAJAXRequest(retrievalURL, responseFunction) {var ajaxreq;if (window.XMLHttpRequest) {
ajaxReq = new XMLHttpRequest();} else if (window.ActiveXObject) {
ajaxReq = new ActiveXObject("Microsoft.XMLHTTP");}ajaxReq.open("GET", retrievalURL);ajaxReq.onreadystatechange = eval(responseFunction);return ajaxReq;
}
Building an AJAX request
All this does is set up the processCan make requestsCan receive back XML
No request has been made (yet)
It doesn’t know what to do with what it gets back (yet)
So, we need a little more code…
To actually make the request…
Need to call the createAJAXRequest() function
Then, pass in two parametersThe URL of the view (or other source of JSON) (as a string)The name of the function to be run when values come back (as a string)
Use the send() method to actually make the call
myAjaxReq = createAJAXRequest(“theURL”, “theFunctionToRun”);
myAjaxReq.send(null);
What you’ll get back…
AJAX objects (XMLHttpRequest, etc) return two things:responseXML (an object)responseText (a string)
For XML, you’d use ajaxReq.responseXML and work directly with the XML DOM in the object
With JSON, you need to use the string value (as it’s not an XML object)
Demo
Make a simple AJAX request from the NAB using a function to do something with the returned values:
function processReturnValue(){alert(ajaxReq.responseText);
}
Needs some cleaning up
It works, but the named function is called every time the request object’s “ready state” changes
LoadingLoadedInteractiveComplete
You don’t need to do things on each state change
Check ready state and status to know when to go
HTTP status values:404 = Not found500 = Internal error100 = Continue200 = Complete (what you want)
function processReturnValue(){if (ajaxReq.readyState == 4) {
if (ajaxReq.status == 200) {alert(ajaxReq.responseText);
}}
}
ReadyState values:0 = uninitialized1 = loading2 = loaded3 = interactive4 = complete
Demo
Make a better AJAX request by tweaking the function slightly
function processReturnValue(){if (ajaxReq.readyState == 4){
if (ajaxReq.state == 200){alert(ajaxReq.responseText);
}}
}
But this is only text…not JavaScript
You must convert the responseText to an actual JSON object before it will be of any use in your code
Conversion to a JavaScript object is done using eval()
var jsonObject = eval(ajaxReq.responseText);
…or possibly…
eval(ajaxReq.responseText);
Using eval() to make it live
function processReturnValue(){if (ajaxReq.readyState == 4) {
if (ajaxReq.status == 200) {eval(“viewJSON=” + ajaxReq.responseText);var viewRows = viewJSON.viewentry;for (var i = 0; i < viewRows.length; i++){
// looping through the rows…docUNID = viewRows[0][“@unid”];alert(docUNID);
}}
}}
Demo
Retrieving JSON from a view, formatting results with HTML
What you have
At this point, all you have are data elements you can easily extract from the JSON and surround with HTML
But, what more do you need?
With HTML you have…JavaScriptDHTMLCSSAnd so on
You have retrieved data from another place, asynchronously, and made it available to whatever you’re doing
Carrying it a bit further
Without a lot of additional work, this could become any number of things:
Entry validationNAB picker (demo)Type-ahead (demo)Or something else
It’s powerful technology and not all that hard to do
Where all can you get JSON from Domino?
Notes ViewsUsing ?ReadViewEntries&OutputFormat=JSON
Notes ViewsCustom JSON objects
Notes Pages
Notes Agents
JavaScript Libraries
JS Header
Computed Text or field in the form
Demos…
AJAX & JSON from a custom view
AJAX & JSON from a Page
AJAX & JSON from an Agent
In summary
Both AJAX and JSON are technologies you should know
Both make web development easier, web applications more powerful
TOGETHER they are even better
The more comfortable you are with them, the more places you’ll find to use them…and the better your apps will be
Legal DisclaimersThe workshops, sessions and materials have been prepared by IBM or the session speakers and reflect their own views. They are provided for informational purposes only, and are neither intended to, nor shall have the effect of being, legal or other guidance or advice to any participant. While efforts were made to verify the completeness and accuracy of the information contained in this presentation, it is provided AS IS without warranty of any kind, express or implied. IBM shall not be responsible for any damages arising out of the use of, or otherwise related to, this presentation or any other materials. Nothing contained in this presentation is intended to, nor shall have the effect of, creating any warranties or representations from IBM or its suppliers or licensors, or altering the terms and conditions of the applicable license agreement governing the use of IBM software.
References in this presentation to IBM products, programs, or services do not imply that they will be available in all countries in which IBM operates. Product release dates and/or capabilities referenced in this presentation may change at any time at IBM’s sole discretion based on market opportunities or other factors, and are not intended to be a commitment to future product or feature availability in any way. Nothing contained in these materials is intended to, nor shall have the effect of, stating or implying that any activities undertaken by you will result in any specific sales, revenue growth or other results.
Performance is based on measurements and projections using standard IBM benchmarks in a controlled environment. The actual throughput or performance that any user will experience will vary depending upon many factors, including considerations such as the amount of multiprogramming in the user's job stream, the I/O configuration, the storage configuration, and the workload processed. Therefore, no assurance can be given that an individual user will achieve results similar to those stated here.
All customer examples described are presented as illustrations of how those customers have used IBM products and the results they may have achieved. Actual environmental costs and performance characteristics may vary by customer.
IBM, the IBM logo, Lotus, Lotus Notes, Notes, Domino, Sametime, WebSphere, and Lotusphere are trademarks of International Business Machines Corporation in the United States, other countries, or both.
Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the United States, other countries, or both.
Microsoft and Windows are trademarks of Microsoft Corporation in the United States, other countries, or both.
Linux is a registered trademark of Linus Torvalds in the United States, other countries, or both.
Other company, product, or service names may be trademarks or service marks of others.
Questions?
Thank you!
Scott Good: [email protected]
614-457-7100 x200
http://www.teamsol.com
http://www.scottgood.com (blog)
PLEASE FILL OUT YOUR EVALUATIONS
Teamwork Solutions