View
2
Download
0
Category
Preview:
Citation preview
The Web: Concepts and Technology
Web ServicesWeb ServicesFeb 10
1Spring 2009Eugene Agichtein CS 190: The Web: Concepts and Technology, Emory University
Today’s PlanToday’s PlanJavascript wrap-up:J p p p
ObjectsFunctionsLoopsEvents
W b S iWeb ServicesXML
2Spring 2009Eugene Agichtein CS 190: The Web: Concepts and Technology, Emory University
Debugging JavaScriptDebugging JavaScript1. Debugging JS is a painI know of two reasonable tools for JS debuggin:
Firebug: https://addons.mozilla.org/en-US/firefox/addon/1843V kM h // dd ill / US/fi f / dd /216VenkMan: https://addons.mozilla.org/en-US/firefox/addon/216
3Spring 2009Eugene Agichtein CS 190: The Web: Concepts and Technology, Emory University
JS TypesypNumbers
Operators: +, -, *, and / as the basic four arithmetic operations. Comparison: < > <= >=Comparison: <, > , <=, >= %, is the remainder operator: if you divide one number by another, this operator gives you the remainder. For example, 7 % 3 is 1.
Strings : “pieces of text” or “sequences of characters.” E.g., "Frodo", "The Lord of the Rings", and "this is a string" are all strings. Strings can be created with double quote character (") or the single quote character ('). The only operator for strings is the concatenation operator, written +, whichThe only operator for strings is the concatenation operator, written , which glues two strings together. E.g. "rail" + "road" is "railroad".
Booleanslogical values that are either true or false.
h 7 13 f l h l h 7 3E.g., the expression (7 > 13) is false while the expression (7 > 3) is true. logic operators for boolean values:
! means not, so !(7 > 13) is true && means and, so (7 > 13) && (7 > 3) is false
4
|| means or, so (7 > 13) || (7 > 3) is true
Spring 2009Eugene Agichtein CS 190: The Web: Concepts and Technology, Emory University
Summarythree basic data types: strings, numbers, and booleans. The basic arithmetic operators + (addition), - (subtraction), * (multiplication), / (division), and % (remainder) are provided for numbers. ( ), ( ) pvariables can be assigned values of any type, including numbers and numeric expressions. When an assignment statement is executed, the expression on the right-hand id i l t d fi t d th th lti l i i d t th i blside is evaluated first, and then the resulting value is assigned to the variable on
the left-hand side. multiplication and division have higher precedence than addition and subtraction. Among operators with the same precedence, expressions are g p p pevaluated in a left-to-right order. When the + operator is applied to a string and a number, the number is automatically converted into a string and then the two are concatenated. The prompt() method al a s returns a string alue e en hen a number isThe prompt() method always returns a string value, even when a number is entered by the user. A string can be converted to number using parseFloat() for parseInt function. variables can be used to store input values, define easily modifiable values, and
5
retain intermediate values in complex computations.
Spring 2009Eugene Agichtein CS 190: The Web: Concepts and Technology, Emory University
User defined functionsUser-defined functions<HEAD> <TITLE> The function template</TITLE> <SCRIPT
TYPE " /J S i ">TYPE = "text/JavaScript">
functionName() {functionName() {. . . JavaScript code to define the function goes here . . . } }
</SCRIPT>
</HEAD>
6Spring 2009Eugene Agichtein CS 190: The Web: Concepts and Technology, Emory University
Function Declaration vs InvocationFunction Declaration vs. Invocation<HTML><HEAD><META http-equiv=Content-Type content="text/html; charset=windows-1252"> <SCRIPT language="JavaScript 2.1" type=text/javascript>type=text/javascript>
function main() {
window.alert("Hello World!"); }}
</SCRIPT> </HEAD> <BODY onload=javascript:main();> <H1 style="TEXT-<BODY onload javascript:main();> <H1 style TEXTALIGN: center">Hello World</H1> <HR width="85%" SIZE=2> </BODY>/HTML
Agichtein for Emory CS171, Spring 20087
</HTML>
Example: Date GenerationExample: Date GenerationSuppose want to date document (e.g., like newspapers do)
<script type = "text/JavaScript"> var today = new Date(); //Date objectvar today = new Date(); //Date objectvar the_day = today.getDate(); //Method invocationvar the_month = today.getMonth(); //Method invocationvar the_year = today.getFullYear(); the_month = the_month + 1; //month starts at zerovar the whole date = the month + "/" + the day + "/" + the year;var the_whole_date the_month / the_day / the_year; document.write(“In CS190, today is " + the_whole_date + "<p>");
</script>
8Spring 2009Eugene Agichtein CS 190: The Web: Concepts and Technology, Emory University
Function SummaryFunction SummaryFunctions encapsulate code for performing common tasks that we're likely to repeat in many contexts. y p y .Function definitions are generally within the HEAD of a document. Function calls are generally within the BODY of a document. Once a function is defined you can call it as often as you likeOnce a function is defined, you can call it as often as you like. A function definition is only that — a definition. Unless a function is called, it will not execute! You call a function with no parameters like this: wisdom();You call a function with no parameters like this: wisdom(); A parameter allows something about the function to change from one invocation to the next. To call a function with a parameter you include a value (or expressionTo call a function with a parameter you include a value (or expression that evaluates to a value) within the parantheses. Your function call must be within <SCRIPT> tags or an event handler.
9Spring 2009Eugene Agichtein CS 190: The Web: Concepts and Technology, Emory University
More about ObjectsMore about ObjectsJavaScript String object
var txt="Hello world!";document.write(txt.toUpperCase());
Complete String reference: http://www.w3schools.com/jsref/jsref_obj_string.asp
10Spring 2009Eugene Agichtein CS 190: The Web: Concepts and Technology, Emory University
A little more about formsA little more about formsSelect Lists
<select name="beverage"> <option>Coke <option>Pepsi <option>Beer <option>Wine
</select>Wh f d d h l f d llWhat if we wanted to update the list of options dynamically:
Courses to drop/add; available shoe sizes for this model, …
11Spring 2009Eugene Agichtein CS 190: The Web: Concepts and Technology, Emory University
LoopsLoops<script type="text/javascript">
for (i = 0; i <=100; i++){for (i = 0; i <=100; i++){document.write(i+ “I will never cross on red again <p>” );
}</ i t></script>Equivalent:
i=0;{while (i<=100) {
document.write("The number is " + i);}
Useful play tool: http://www.w3schools.com/js/tryit.asp?filename=tryjs_fornext
12
p j y p yj
Spring 2009Eugene Agichtein CS 190: The Web: Concepts and Technology, Emory University
JavaScript ArraysJavaScript ArraysThe Array object is used to store multiple values in a single variablevariable. Complete Reference: http://www.w3schools.com/jsref/jsref_obj_array.asp
var myCars=new Array();myCars[0]="Saab"; myCars[1]="Volvo";myCars[1]= Volvo ; myCars[2]="BMW";
Access to Array elements:ydocument.write(myCars[0]);myCars[0]="Opel";
13Spring 2009Eugene Agichtein CS 190: The Web: Concepts and Technology, Emory University
Arrays + Loops = GoodnessArrays + Loops = Goodness
" "<script type="text/javascript">var myCars=new Array(“Saab”, “Volvo”, “BMW”);f (i 0 i < C l th i++){for (i = 0; i <myCars.length; i++){
document.write(myCars[i]+ “<br>” );}}
</script>
14Spring 2009Eugene Agichtein CS 190: The Web: Concepts and Technology, Emory University
EventsEventsThere are common JavaScript events defined on most HTML page elements. You can write JavaScript code that runs if and when one of these events takes placethese events takes place. Example: http://cs190.mathcs.emory.edu/~cs190000/feb10/JavaScript code whose execution is triggered by an event isJavaScript code whose execution is triggered by an event is called an event handler.Important events: onload and onSubmitpOther common JavaScript Events:http://www.htmlhelp.com/reference/html40/attrs.html#events
15Spring 2009Eugene Agichtein CS 190: The Web: Concepts and Technology, Emory University
JavaScript: Processing Form DataJavaScript: Processing Form DataForm validation is the process of checking that the information provided by the user is correct (or not obviously incorrect) before processing it.y ( y ) p g .
<form action=http://www.google.com/searchonsubmit="return validate(this);" >
<label for="q">Search:</label> <input type="text" name="q" id="q">
</form>…
f ti lid t (f) {function validate(f) { if(f.q.value=="") {
return false; }}else{ return true; }
}
16Spring 2009Eugene Agichtein CS 190: The Web: Concepts and Technology, Emory University
“Web 2 0”Web 2.0Event-driven programming model that involves calling web service APIs by sending and receiving messagesin XML format over the HTTP protocol.
Today we’ll just cover the basics to give you background ft th t h ld b bl t f ll / dif– after that you should be able to follow/modify
examples in the (many) online tutorials to do what you needneed
Agichtein for Emory CS171, Spring 200817
IntuitionIntuitionWeb service API: collection of function definitionsWeb service API call: invocation of a Web Service function
Example: Yahoo Search APIDefinition:I tiInvocation:
18Spring 2009Eugene Agichtein CS 190: The Web: Concepts and Technology, Emory University
What is a web service?What is a web service?“A software system designed to support interoperableA software system designed to support interoperable machine-to-machine interaction over a network. It has an interface described in a machine-processable format.” -W3C
⇒WSDL and SOAP conveyed using HTTP with an XML serialization + other Web-related standards
Example Web services:Amazon (http://www.amazon.com/gp/aws/landing.html)Yahoo (http://developer.yahoo.net)eBay (http://developer.ebay.com/rest)y ( p p y )Flickr (http://www.flickr.com/services/)YouTube (http://www.youtube.com/api2_rest)Del.icio.us (http://del.icio.us/doc/api)
Agichtein for Emory CS171, Spring 200819
Del.icio.us (http://del.icio.us/doc/api)
Web Service modelsResource oriented model
A resource is anything that can have an identifier (URI)Focuses on resource description and representation (data objectFocuses on resource description and representation (data object reflecting state of resource)
Service oriented modelA service is realised by an agent (provider) and used by another (requester)Focuses on tasks (unit of action) that may be performed by an agent: ( ) y p y gdescription, messaging/choreography and goal state
Message oriented modelA i h b i i f d f h hA message is the basic unit of data sent from one agent to another: the action taken in response to receiving a message is up to the recipientFocuses on message structure (contract) and transport (choice of
Agichtein for Emory CS171, Spring 200820
protocol carries no semantics)
AJAX (Asynchronous Javascript + XML)
Uses browser’s XML support: DOM, XSLTXMLHttpRequestXMLHttpRequestGoogle Maps is best-known AJAX application
Agichtein for Emory CS171, Spring 200821
AJAX Design PrinciplesAJAX Design Principles1. The browser hosts an application, not content
A li ti d d li d t b tl J S i t dApplication code delivered to browser, mostly as JavaScript code
2. The server delivers data, not contentData may be plain text, JavaScript fragments, or XML documents
3. User/application interaction is continuous and fluidUI metaphors like drag-and-drop become possible
4.This is real coding and requires discipline4. This is real coding and requires disciplineSignificant developer responsibility to manage conversational state over entire web transaction
Agichtein for Emory CS171, Spring 200822
Basic AJAX processBasic AJAX process
Agichtein for Emory CS171, Spring 200823
The src AttributeThe src AttributeWe can link external JavaScript applications using the src J p pp gattribute:
<script type="text/javascript"language="JavaScript 2.1"src "scripts/hiThere js"src="scripts/hiThere.js">
Agichtein for Emory CS171, Spring 200824
Si l D t E h g F t JSONSimple Data Exchange Format: JSONJSON (JavaScript Object Notation, RFC-4627)J (J p j , )
Subset of JS object literal notation (does not require JS)Data types: number, string, boolean, array, object, nullSupported by many languagesIn Dec 2005, Yahoo! added support for JSON
butbutNo schema mechanism (validation, code generation)Limited type system (no date or time)yp yNo extension or versioning
Agichtein for Emory CS171, Spring 200825
Data InterchangeData InterchangeThe key idea in Ajax.
An alternative to page replacement.
Applications delivered as pages.
How should the data be delivered?
Agichtein for Emory CS171, Spring 200826
JSONJSONJavaScript Object Notation
Minimal
Textual
Subset of JavaScript
Agichtein for Emory CS171, Spring 200827
ValuesValuesStringsNumbersBooleans
ObjectsArrays
llnull
Agichtein for Emory CS171, Spring 200828
ObjectObjectObjects are unordered containers of key/value pairsObjects are wrapped in { }, separates key/value pairs: separates keys and valuesKeys are strings Values are JSON values
struct record hashtable objectstruct, record, hashtable, object
Agichtein for Emory CS171, Spring 200829
ObjectObject
Agichtein for Emory CS171, Spring 200830
ObjectObject{
" " "J k B Ni bl ""name": "Jack B. Nimble",
"at large": true,
"grade": "A""grade": "A",
"format": {
"type": "rect",type : rect ,
"width": 1920,
"height": 1080,
"interlace": false,
"framerate": 24
Agichtein for Emory CS171, Spring 200831
}
}
ArrayArrayArrays are ordered sequences of valuesArrays are wrapped in [], separates values JSON does not talk about indexing.
An implementation can start array indexing at 0 or 1.
Agichtein for Emory CS171, Spring 200832
ArrayArray["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
[[0, -1, 0],[0, 1, 0],
[1, 0, 0],
[0, 0, 1]
]
Agichtein for Emory CS171, Spring 200833
Arrays vs ObjectsArrays vs ObjectsUse objects when the key names are arbitrary strings.
Use arrays when the key names are sequential integers.
Don't get confused by the term Associative Array.
Agichtein for Emory CS171, Spring 200834
JSON in AjaxJSON in AjaxHTML Delivery.
JSON data is built into the page.<html>...
<script>
var data = { JSONdata };var data = { ... JSONdata ... };
Agichtein for Emory CS171, Spring 200835
JSON in AjaxJSON in AjaxXMLHttpRequest
Obtain responseTextParse the responseText
responseData = eval(
'(' + responseText + ')');
responseData =
responseText.parseJSON();
Agichtein for Emory CS171, Spring 200836
JSON in AjaxJSON in AjaxSecret <iframe>Request data using form.submit to the <iframe> target.The server sends the JSON text embedded in a script in a document.
h l h d i<html><head><script>
document.domain = 'penzance.com';
parent.deliver({ ... JSONtext ... });parent.deliver({ ... JSONtext ... });
</script></head></html>
The function deliver is passed the value.
Agichtein for Emory CS171, Spring 200837
p
JSON in AjaxJSON in AjaxDynamic script tag hack.Create a script node. The src url makes the request.The server sends the JSON text embedded in a script.deliver({ JSONtext });deliver({ ... JSONtext ... });
The function deliver is passed the value.The dynamic script tag hack is insecure.y p g
Agichtein for Emory CS171, Spring 200838
JSONRequestJSONRequestA new facility.Two way data interchange between any page and any server.Exempt from the Same Origin Policy.Campaign to make a standard feature of all browsers.
http://www.JSON.org/JSONRequest.html
Agichtein for Emory CS171, Spring 200839
JSON Looks Like DataJSON Looks Like DataJSON's simple values are the same as used in programming llanguages.
No restructuring is required: JSON's structures look likeNo restructuring is required: JSON s structures look like conventional programming language structures.
JSON's object is record, struct, object, dictionary, hash, associate array...
JSON's array is array, vector, sequence, list...
Agichtein for Emory CS171, Spring 200840
Yahoo Web Service with JSONYahoo Web Service with JSON
Tutorial/Howto:
http://developer.yahoo.com/common/json.html
Can use nice interface widgets:Can use nice interface widgets:http://developer.yahoo.com/yui/index.htmlhttp://developer.yahoo.com/yui/examples/datatable/dt_xhrjson.html
Agichtein for Emory CS171, Spring 200841
JSON ExampleJSON ExampleBy default the Yahoo! Web Services return output in XML format. To get output in JSON format use the output=json parameter inTo get output in JSON format, use the output=json parameter in the request:
http://search.yahooapis.com/ImageSearchService/V1/imageSearch d h dh?appid=YahooDemo&query=Madonna&output=json
Key idea: Callback function. The callback parameterKey idea: Callback function. The callback parameter (callback=function) wraps the JSON output text in parentheses and a function name (e.g., MyFunction)http://search yahooapis com/ImageSearchService/V1/imageSeahttp://search.yahooapis.com/ImageSearchService/V1/imageSearch?appid=YahooDemo&query=Madonna&output=json&callback=MyFunction
42Spring 2009Eugene Agichtein CS 190: The Web: Concepts and Technology, Emory University
Complete ExampleComplete Example<html>
<head> <title>How Many Pictures Of Madonna Do We Have?</title> y</head> <body>
<script type="text/javascript">function myFunction(obj) { alert(obj.ResultSet.totalResultsAvailable); }
</script></script> <script type="text/javascript" src="http://search.yahooapis.com/ImageSearchService/V1/imageSearch?appid=YahooDemo&query=Madonna&output=json&callback=myFunction"></script></script>
</body> </html>
43Spring 2009Eugene Agichtein CS 190: The Web: Concepts and Technology, Emory University
Can we do something more i t ti g?interesting?
Display first 10 images of results
for(i=0; i<obj.ResultSet.totalResultsAvailable && i<10; i++){var img = obj.array[i];//do something with the image, like write to document!
}
44Spring 2009Eugene Agichtein CS 190: The Web: Concepts and Technology, Emory University
Recommended