asynchronous javascript and xml

25
Asynchronous JavaScript and XML (AJAX)

Upload: anwesh-reddy

Post on 14-Apr-2017

479 views

Category:

Documents


6 download

TRANSCRIPT

Page 1: Asynchronous JavaScript and XML

Asynchronous JavaScriptand XML (AJAX)

Page 2: Asynchronous JavaScript and XML

Asynchronous JavaScript and XML (AJAX)

• Asynchronous JavaScript and XML (AJAX) refers to a combination of technologies that allows Web pages displayed on a client computer to quickly interact and exchange data with a Web server without reload- ing the entire Web page.

• The key component of AJAX, the XMLHttpRequest object that uses HTTP to exchange data between a client computer and a Web server. Unlike standard HTTP requests, which usually replace the entire page in a Web browser, the XMLHttpRequest object can be used to request and receive data without reloading a Web page. By combining the XMLHttpRequest object with DHTML techniques, you can update and modify individual portions of your Web page with data received from a Web server.

Page 3: Asynchronous JavaScript and XML

AJAX’s Limitations• You cannot use the XMLHttpRequest object to directly

access content on another domain’s server; the data you request with the XMLHttpRequest object must be located on the Web server where your JavaScript program is running or originated.

• However, you can use a server-side script as a proxy to access data from another domain.

Page 4: Asynchronous JavaScript and XML

Accessing content on another domain• You can use a server-side script to access data from another

domain, particularly when it comes to accessing Web services and RSS feeds.

• A Web service, or XML Web service, is a software component that resides on a Web server. Web services simply provide services and data in the form of methods and properties;

Page 5: Asynchronous JavaScript and XML

Creating an AJAX’s script• Instantiate an XMLHttpRequest object for the Web

browser where the script will run. • Use the XMLHttpRequest object to send a request to the

server. • Read and process the data returned from the server

Page 6: Asynchronous JavaScript and XML

HTTP Messages• When you submit a request for a Web page, the HTTP client

opens a connection to the server and submits a request message. The Web server then returns a response message

• Both request and response messages are in the following format:

Start line containing the request method for requests or status line for responses Header lines (zero or more) Blank line Message body (optional)

• The first line either identifies the method (such as “get” or “post”) for requests or the status returned from a response. Following the first line, each message can include zero or more lines containing headers, which define information about the request or response message and about the contents of the message body.

Page 7: Asynchronous JavaScript and XML

HTTP Headers (1)• The RFC2616 recommendation defines 46 HTTP 1.1 headers, categorized

by generic headers that can be used in request or response messages and headers that are specific to a request, a response, or the message body. The format for using a header is header: value.

• For example, Connection: close Date: Sun. , 19 October 201418:32:07 GMT The Connection header specifies that the HTTP connection should close after the Web client receives a response from the Web server.

• The Date header identifies the date and time in Greenwich Mean Time format when a message was originated.

• The Cache-Control header, which specifies how a Web browser should cache any server content it receives. While this is enabled, it improves Web browser performance, but it goes against the reason for using AJAX, which is to dynamically update portions of a Web page with the most recent data from a server. you should always include in your AJAX programs the Cache-Control header, assigned a value of “no- cache”, as follows:

Cache-Control:no-cache

Page 8: Asynchronous JavaScript and XML

HTTP Messages (2)• A blank line always follows the last header line. • Optionally, a message body can follow the blank line in the • messages. • The typical message body can contain:

The form data for “post” requests Some type of document (such as a Web page or XML page) Other type of content (such as an image file)

• However, message bodies are not required for either request or response messages. For example, with a “get” request, no message body is necessary because any form data that is part of the request is appended to the URL.

• Besides POST and GET. there are five other methods that can be used with an HTTP request: HEAD, DELETE, OPTIONS, PUT, and TRACE.

• The HEAD method is commonly used for returning information about a document, but not the document itself

Page 9: Asynchronous JavaScript and XML

HTTP Requests• The “get” method is used for standard Web page requests but can have

a query string or form data appended to the URL. • If you enter the adderss (http://www.npu.edu) in your Web browser, the

browser creates a request message that begins with the following start line:

GET/HTTP/1.1 • If you enter the address (http://www.npu.edu/admissions/

application.html) in you web browser, the following will be the first line of the generalized message.

GET /admissions/application.html HTTP/1.1 • The most web browser will include the following headers:

Host Identifies the host portion of a requested URL Accept-Encoding Defines the encoding formats that the HTTP client accepts Accept Defines the MIME types that the HTTP client accepts Accept-Language Lists the languages that the HTTP client accepts in a response Accept-Charset Defines the character sets that the HTTP client accepts User-Agent identifies the user agent, such as a Web browser, that submitted the request Referrer Identifies the referring URL from which the request was made

Page 10: Asynchronous JavaScript and XML

Example of requesting secure.npu.edu

Page 11: Asynchronous JavaScript and XML

HTTP Posts• A “post” request is similar to a “get” request, except that any

submitted data is included in the message body, immediately following the blank line after the last header. Also usually include some of the headers listed below:

Content-Encoding Defines the encoding format of the message body Content-Language Identifies the language of the message body Content-Length Identifies the size of the message body Content-Location Specifies the location of the message body contents Content-Type Identifies the MIME type of the message body Expires Defines the expiration date of the message body contents Last-Modified Identifies the last modifiation date of the message body contents

Page 12: Asynchronous JavaScript and XML

Example of using POST method

Page 13: Asynchronous JavaScript and XML

HTTP Response• HTTP response messages take the same format as request

messages, except for the contents of the start line and the headers. Instead of containing a request method, the start line (also known as the status line), returns the protocol and version of the HTTP server (such as HTTP/1.1) along with a status code and descriptive text.

• The status codes returned from an HTTP server consist of three digits.

1xx (informational)—Request was received 2xx: (success)—Request was successful e.g 200 OK 3xx: (redirection)—Request cannot be completed without further action 4xx: (client error)—Request cannot be fulfilled due to a client error e.g. 404 Not found 5xx: (server error)— Request cannot be fulfilled due to a server error e.g. 500 Internal Server Error

Page 14: Asynchronous JavaScript and XML

Example of Response Header

Page 15: Asynchronous JavaScript and XML

Example of Response Body

Page 16: Asynchronous JavaScript and XML

Example of creating your own response message (1)<!DOCTYPE html> <html> <head> <title>Top News</title> <meta charset="UTF-8"> </head> <body> <h1>Top News</h1> <form method="post" action="http://local host:8080"> <table border="1" width="100%"> <tr> <td valign="top"> <input type="radio" name="agency" value="http://my.abcnews.go.com/rsspublic/fp_rss20.xml" checked="checked" /> ABC News<br /> <input type="radio" name="agency" value="http://newsrss.bbc.co.uk/rss/newsonline_uk_edition/front_page/rss.xml" /> BBC<br /> <input type="radio" name="agency" value="http://www.cbsnews.com/feeds/rss/main.rss" /> CBS News<br /> <input type="radio" name="agency" value="http://rss.cnn.com/rss/cnn_topstories.rss" /> CNN<br /> <input type="radio" name="agency" value="http://rss.msnbc.msn.com/id/3032091/device/rss/rss.xml" /> MSNBC<br /> <input type="radio" name="agency" value="http://rss.news.yahoo.com/rss/topstories" /> Yahoo! News </td> <td id="newsCell" width='30%' align="top"> </td> </tr> </table> <p><input type="submit" value="Get Headlines" /></p> </form> </body> </html>

Page 17: Asynchronous JavaScript and XML

Example of creating your own response message (proxy_nodejs.js)

var http = require('http'); var url = require('url'); var request = require('C:\\Users\\kcheung\\node_modules\\request');

function handle_incoming_request(req, res) { console.log("INCOMING REQUEST: " + req.method + " " + req.url); req.parsed_url = url.parse(req.url, true); var getp = req.parsed_url.query; var agency = getp.agency ? getp.agency : ""; console.log("agency: " + agency);

res.writeHead(200, {"Content-Type": "text/xml"}); request(agency, function (error, response, body) { if (!error && response.statusCode == 200) { res.end(body); } }); } var s = http.createServer(handle_incoming_request); s.listen(8080);

Page 18: Asynchronous JavaScript and XML

The XMLHttpRequest Object’s Methods• The XMLHttpRequest object allows you to use JavaScript and HTTP to

exchange data between a Web browser and a Web server. • The XMLHttpRequest object’s methods:

abort() Cancels the current HTTP request getAllResponseHeaders() Returns a text string containing all of the headers that were returned with a response in header: value format, separated by line breaks getResponseHeader(header_name) Returns a text string containing the value assigned to the specifi ed header open(method,URL[,async,user, password]) Specifies the method and URL for an HTTP request; assigning a value of true to the async argument performs the request asynchronously, while a value of false performs the request synchronously; the default is true send([content]) Submits an HTTP request using the information assigned with the open() method; the optional content argument contains the message body setRequestHeader(header_name, value) Creates an HTTP header using the header_name and value arguments

Page 19: Asynchronous JavaScript and XML

The XMLHttpRequest Object’s Properties• onreadystatechange Specifi es the name of the event

handler function that executes whenever the value changes that is assigned to the readyState property

• readyState Contains one of the following values, which represent the state of the HTTP request: 0 (uninitialized), 1 (open), 2 (sent), 3 (receiving), or 4 (loaded)

• responseText Contains the HTTP response as a text string

• responseXML Contains the HTTP response as an XML document

• status Contains the HTTP status code (such as 200 for “OK” or 404 for “Not Found”) that was returned with the response

• statusText Contains the HTTP status text (such as “OK” or “Not Found”) that was returned with the response

Page 20: Asynchronous JavaScript and XML

Using the XMLHttpRequest Object• The first step is to instantiate an XMLHttpRequest object

var httpRequest = new XMLHttpRequest(); • You use the open() method with the instantiated XMLHttpRequest object to

specify the request method (such as “get” or “post”) and URL. httpRequest.open("get","StockCheck.php?" + "checkQuote=" + tickerSymbol);

• The open() method also accepts three optional arguments. async, can be assigned a value of true or false to determine whether the request will be handled synchronously or asynchronously. Username is only necessary if the Web server requires authentication. Password is only necessary if the Web server requires authentication.

• Example httpRequest.open("get","StockCheck.php?" + "checkQuote=" + tickerSymbol, false, “user”, “password”);

• You use the send() method with the instantiated XMLHttpRequest object to submit the request to the server. The send() method accepts a single argument containing the message.

Page 21: Asynchronous JavaScript and XML

The XMLHttpRequestGet.html<!DOCTYPE html> <html> <head> <title>TODO supply a title</title> <meta charset="UTF-8"> <script type="text/javascript"> var newsRequest = false; function getRequestObject() { try { httpRequest = new XMLHttpRequest(); httpRequest.open("get", "http://local host:8080?" + "url="

+ document.myform.url.value, false); httpRequest.send(null); document.write(httpRequest.responseText); } catch (requestError) { window.alert("Your browser does not support AJAX!"); return false; } } </script> </head> <body> <form name="myform" action=""> <input type="text" name="url" size="100" value="" /><br> <input type="button" onclick="getRequestObject()" value="Go to NPU" /> </form> </body> </html>

Page 22: Asynchronous JavaScript and XML

The proxy_nodejs.jsvar http = require('http'); var url = require('url'); var request = require('C:\\Users\\kcheung\\node_modules\\request');

function handle_incoming_request(req, res) { console.log("INCOMING REQUEST: " + req.method + " " + req.url); req.parsed_url = url.parse(req.url, true); var getp = req.parsed_url.query; var agency = getp.agency ? getp.agency : ""; console.log("agency: " + agency);

res.writeHead(200, {"Content-Type": "text/xml"}); request(agency, function (error, response, body) { if (!error && response.statusCode == 200) { res.end(body); } }); } var s = http.createServer(handle_incoming_request); s.listen(8080);

Page 23: Asynchronous JavaScript and XML

The TopNews using synchronized AJAX call<script type="text/javascript"> var newsRequest = false; function getRequestObject() { try { httpRequest = new XMLHttpRequest(); } catch (requestError) { window.alert("Your browser does not support AJAX!"); return false; } return httpRequest; } function newsUpdate() { if (!newsRequest) newsRequest = getRequestObject(); for (var i = 0; i < 6; ++i) { if (document.forms[0].agency[i].checked == true) { var agency = document.forms[0].agency[i].value; break; } } newsRequest.abort(); newsRequest.open("get", "http://localhost:8080?" + "agency=" + agency, false); newsRequest.send(null); var news = newsRequest.responseXML; document.getElementById("newsCell").innerHTML = ""; var newsItems = news.getElementsByTagName("item"); if (newsItems.length > 0) { for (var i = 0; i < newsItems.length; ++i) { var curHeadline = newsItems[i].getElementsByTagName("title")[0].firstChild.nodeValue; var curLink = newsItems[i].getElementsByTagName("link")[0].firstChild.nodeValue; var curPubDate = newsItems[i].getElementsByTagName("pubDate")[0].firstChild.nodeValue; var curDesc = newsItems[i].getElementsByTagName("description")[0].firstChild.nodeValue; var curStory = "<a href='" + curLink + "'>" + curHeadline + "</a><br />"; curStory += "<span style='color: gray'>" + curPubDate + "</span><br />"; curStory += curDesc + "<br />"; document.getElementById("newsCell").innerHTML += curStory; } } else document.getElementById("newsCell").innerHTML = "RSS feed does not contain any items."; } </script>

Page 24: Asynchronous JavaScript and XML

Asynchronous requests and responses• An asynchronous request allows JavaScript to continue processing

while it waits for a server response. • To create an asynchronous request, you pass a value of true as the

third argument of the open() method or omit the argument altogether. • To receive a response for an asynchronous request, you must use

the XMLHttpRequest object’s readyState property and onreadystatechange event. • The readyState property contains one of the following values,

which represents the state of the HTTP request: 0 (uninitialized), 1 (open), 2 (sent), 3 (receiving), or 4 (loaded).

• The onreadystatechange event is triggered whenever the value assigned to the readyState property changes. You assign to the onreadystatechange event the name of a function that will execute whenever the readyState property changes.

• Note that you cannot process the response until the readyState property is assigned a value of 4, meaning that the response is finished loading.

Page 25: Asynchronous JavaScript and XML

The XMLHttpRequestGet_Async.html

<!DOCTYPE html> <html> <head> <title>TODO supply a title</title> <meta charset="UTF-8"> <script type="text/javascript"> var httpRequest = false; function getRequestObject() { try { httpRequest = new XMLHttpRequest(); httpRequest.open("get", "http://local host:8080?" + "url=" + document.myform.url.value, true); httpRequest.send(null); httpRequest.onreadystatechange=processResponse; } catch (requestError) { window.alert("Your browser does not support AJAX!"); return false; } } function processResponse() { if (httpRequest.readyState==4 && httpRequest.status == 200) { document.write(httpRequest.responseText); } } </script> </head> <body> <form name="myform" action=""> <input type="text" name="url" size="100" value="" /><br> <input type="button" onclick="getRequestObject()" value="Go to NPU" /> </form> </body> </html>