introduction to json & ajax

Post on 14-Feb-2017

121 Views

Category:

Technology

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Introduction to JSON & AJAX

www.collaborationtech.co.inBengaluru INDIA

Presentation By Ramananda M.S Rao

JSONContentWhat is JSON ?Where JSON is used ?JSON Data Types and ValuesObject ArraysReading JSON data structureWhere JSON is used ?Data InterchangeJSON vs. XMLJSON in AJAXXMLHttpRequestAJAXPOST and GET calls in AJAX Ajax Methods and PropertiesAJAX client Server InteractionsBenefits of AjaxCurrent Issues of AJAXJSONHttpRequestJSON LimitationsAbout Us

www.collaborationtech.co.in

Introduction to JSONWhat is JSON?JSON stands for JavaScript Object Notation. JSON objects are used for transferring data between server and client.JSON is a subset of JavaScript. ( ECMA-262 ).Language Independent, means it can work well with most of the modern programming languageText-based, human readable data exchange formatLight-weight. Easier to get and load the requested data quickly.Easy to parse.JSON has no version and No revisions to the JSON grammar.JSON is very stableCharacter Encoding is Strictly UNICODE. Default: UTF-8. Also UTF-16 and UTF-32 are allowed.official Internet media type for JSON is application/json.JSON Is Not XML.JSON is a simple, common representation of data.

www.collaborationtech.co.in

JSON DATA TYPES AND VALUESJSON DATA TYPES AND VALUESStringsNumbersBooleansObjectsArraysnull

www.collaborationtech.co.in

Object and ArraysObject Objects are unordered containers of key/value pairs Objects are wrapped in { } , separates key/value pairs : separates keys and values Keys are strings Values are JSON values - struct,record,hashtable,objectArray Arrays are ordered sequences of values Arrays are wrapped in [] , separates values An implementation can start array indexing at 0 or 1.

www.collaborationtech.co.in

JSON data: JSON data: It basically has key-value pairs.var chaitanya = { "firstName" : "Chaitanya", "lastName" : "Singh", "age" : "28"};

We can access the information out of a JSON object like this:

document.writeln("The name is: " +chaitanya.firstName);document.writeln("his age is: " + chaitanya.age);document.writeln("his last name is: "+ chaitanya.lastName);

www.collaborationtech.co.in

Parsing JSONTo get the value 1880 marked with red color:o We can use a.John.data[0][0]JSON.stringify(): Takes a JavaScript object and produces a JSON string from it.JSON.parse(): Takes a JSON string and parses it to a JavaScript object.

Parsing JSON in JavaScript

Start with a basic JSON string:var json = '{ "person" : { "age" : 20, "name" : "Jack" } }';Right now, all JavaScript sees here is a string. It doesn’t know it’s actually JSON. You can pass it through to JSON.parse() to convert it into a JavaScript object:var parsed = JSON.parse(json);console.log(parsed);This gives you:{ person: { age: 20, name: 'Jack' } }It is now a regular JavaScript object and you can access properties, just as you’d expect, using either notation:console.log(parsed.person);console.log(parsed.person["age"]);

www.collaborationtech.co.in

Parsing JSONYou can do the opposite and turn an object into a string:var json = {person: {age: 20,name: "Jack"}}console.log(JSON.stringify(json));This gives you a string containing the following:{"person":{"age":20,"name":"Jack"}}

www.collaborationtech.co.in

Reading JSON data structure Reading JSON data structure Samples data: { "firstName": "John", "lastName": "Smith", "age": 25, "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": "10021" }, "phoneNumber": [ { "type": "home", "number": "212 555-1234" }, { "type": "fax", "number": "646 555-4567" } ] }

www.collaborationtech.co.in

AJAXAJAX, or Asynchronous JavaScript and XML. Describes a Web development technique for creating interactive

Web applications using a combination of HTML (or XHTML) and Cascading Style Sheets for presenting information; Document Object Model (DOM).

JavaScript, to dynamically display and interact with the information presented; and the XMLHttpRequest object to interchange and manipulate data asynchronously with the Web server.

It allows for asynchronous communication, Instead of freezing up until the completeness, the browser can communicate with server and continue as normal.

www.collaborationtech.co.in

POST and GET calls in AJAX POST and GET calls in AJAX GET places arguments in the query string, but POST doesn’t.No noticeable difference in AJAX - AJAX request does not appear in the address bar.GET call in AJAX still has the size limitation on the amount of data that can be passed.General principle:GET method: it is used to retrieve data to display in the page and the data is not expected to be changed on the server.POST method: it is used to update information on the server

www.collaborationtech.co.in

Ajax Methods and PropertiesAjax Methods and Properties

Abort() : Aborts the request if it has already been sent.getAllResponseHeaders() : Returns all the response headers as a string..getResponseHeader("headerLabel") : Returns the text of a specified header.open("method", "URL"[,asyncFlag[, "userName"[,"password"]]]) :Initializes a request. This method is to be used from JavaScript code;to initialize a request from native code, use openRequest() instead.send(content) :Sends the request. If the request is asynchronous (which is thedefault), this method returns as soon as the request is sent. If the( ) request is synchronous, this method doesn't return until the responsehas arrived.setRequestHeader("label", "value") : Sets the value of an HTTP request header

www.collaborationtech.co.in

XMLHttpRequest<!DOCTYPE html><html><body>

<div id="demo"><h2>Let AJAX change this text</h2></div>

<button type="button" onclick="loadDoc()">Change Content</button>

<script>function loadDoc() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (xhttp.readyState == 4 && xhttp.status == 200) { document.getElementById("demo").innerHTML = xhttp.responseText; } }; xhttp.open("GET", "ajax_info.txt", true); xhttp.send();}</script>

</body></html>

www.collaborationtech.co.in

Example<!DOCTYPE html><head><title>Ajax Test</title><script type="text/javascript"> var xmlHttp = new XMLHttpRequest(); xmlHttp.open("GET", "hello.txt", true); xmlHttp.addEventListener("load", ajaxCallback, false); xmlHttp.send(null); function ajaxCallback(event){ alert( "Your file contains the text: " + event.target.responseText ); }</script></head><body></body></html>

www.collaborationtech.co.in

Example<!DOCTYPE html><html><body>

<h2>My CD Collection:</h2>

<button type="button" onclick="loadDoc()">Get my CD collection</button>

<p id="demo"></p> <script>function loadDoc() { var xhttp, xmlDoc, txt, x, i; xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (xhttp.readyState == 4 && xhttp.status == 200) { xmlDoc = xhttp.responseXML; txt = ""; x = xmlDoc.getElementsByTagName("COMPANY"); for (i = 0; i < x.length; i++) { txt = txt + x[i].childNodes[0].nodeValue + "<br>"; } document.getElementById("demo").innerHTML = txt; } }; xhttp.open("GET", "cd_catalog.xml", true); xhttp.send();}</script>

</body></html>

www.collaborationtech.co.in

cd_catalog<?xml version="1.0" encoding="UTF-8"?><CATALOG><CD><TITLE>Software Development</TITLE><COURSE>Java,Python,Web Design etc</COURSE><COUNTRY>INDIA</COUNTRY><COMPANY>Collaboration Technologies</COMPANY></CD></CATALOG>

www.collaborationtech.co.in

Follow us on SocialFacebook: https://www.facebook.com/collaborationtechnologies/Twitter : https://twitter.com/collaboration09Google Plus : https://plus.google.com/100704494006819853579LinkedIn : https://www.linkedin.com/in/ramananda-rao-a2012545Instagram : https://instagram.com/collaborationtechnologiesYouTube : https://www.youtube.com/channel/UCm9nK56LRbWSqcYWbzs8CUgSkype : msrnandaWhatsApp : +91 9886272445

www.collaborationtech.co.in

THANK YOU

About Us

top related