Understand about what JSON is
Understand the difference between JSON and XML
Understand the context of using JSON with AJAX
Know how to read and write JSON data using PHP
JSON (JavaScript Object Notation) is an independent data exchange format. It is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. In JSON, a data structure is a key / value pair. It is a subset of the JavaScript Specification (ECME-Script) and is therefore directly in JavaScript.
JSON (JavaScript Object Notation) is an independent data exchange format. It is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. In JSON, a data structure is a key / value pair. It is a subset of the JavaScript Specification (ECME-Script) and is therefore directly in JavaScript.
PHP stands for “PHP: Hypertext Preprocessor”. It is very good for creating dynamic content. PHP is a widely-used, free, and efficient alternative to competitors such as Microsoft's ASP.
JavaScript is an object-based scripting language that is lightweight and cross-platform.
JavaScript is a solution of client side dynamic pages.
JavaScript is helpful in designing interactive web-pages.
This year ECMA International will be ratifying the biggest update to the JavaScript language in its history. In this talk we'll look at key features already appearing in browsers as well as those coming in the near future. We'll also explore how you can begin leveraging the power of ES6 across all browsers today. If you haven't looked at JavaScript recently, you soon realize that a bigger, better world awaits.
In JavaScript, almost "everything" is an object.
-Booleans can be objects (if defined with the new keyword)
-Numbers can be objects (if defined with the new keyword)
-Strings can be objects (if defined with the new keyword)
-Dates are always objects
-Maths are always objects
-Regular expressions are always objects
-Arrays are always objects
-Functions are always objects
-Objects are always objects
Things you should know about Javascript ES5. A programming language that enables you to create dynamically updating content, control multimedia, animate images, and pretty much everything else
JavaScript - Chapter 4 - Types and StatementsWebStackAcademy
A computer program is a list of "instructions" to be "executed" by a computer.
In a programming language, these programming instructions are called statements.
A JavaScript program is a list of programming statements.
JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.
This statement tells the browser to write "Hello Dolly." inside an HTML element with id="demo":
JavaScript Data Types
JavaScript variables can hold many data types: numbers, strings, objects and more.
In programming, data types is an important concept.
To be able to operate on variables, it is important to know something about the type.
What is the DOM?
The DOM is a W3C (World Wide Web Consortium) standard.
The DOM defines a standard for accessing documents:
"The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document."
The W3C DOM standard is separated into 3 different parts:
Core DOM - standard model for all document types
XML DOM - standard model for XML documents
HTML DOM - standard model for HTML documents
The HTML DOM (Document Object Model)
When a web page is loaded, the browser creates a Document Object Model of the page.
The HTML DOM model is constructed as a tree of Objects.
With the HTML DOM, JavaScript can access and change all the elements of an HTML document.
Slide ini merupakan tutorial dasar dari penggunaan javaScript. Bagaimana javascript berjalan dan penggunaannya, javaScript statement, javaScript variable, javaScript looping, dan javaScript operator.
JSON stands for JavaScript Object Notation. JSON objects are used for transferring data between server and client.
JSON Is Not XML.
JSON is a simple, common representation of data.
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.
PHP stands for “PHP: Hypertext Preprocessor”. It is very good for creating dynamic content. PHP is a widely-used, free, and efficient alternative to competitors such as Microsoft's ASP.
JavaScript is an object-based scripting language that is lightweight and cross-platform.
JavaScript is a solution of client side dynamic pages.
JavaScript is helpful in designing interactive web-pages.
This year ECMA International will be ratifying the biggest update to the JavaScript language in its history. In this talk we'll look at key features already appearing in browsers as well as those coming in the near future. We'll also explore how you can begin leveraging the power of ES6 across all browsers today. If you haven't looked at JavaScript recently, you soon realize that a bigger, better world awaits.
In JavaScript, almost "everything" is an object.
-Booleans can be objects (if defined with the new keyword)
-Numbers can be objects (if defined with the new keyword)
-Strings can be objects (if defined with the new keyword)
-Dates are always objects
-Maths are always objects
-Regular expressions are always objects
-Arrays are always objects
-Functions are always objects
-Objects are always objects
Things you should know about Javascript ES5. A programming language that enables you to create dynamically updating content, control multimedia, animate images, and pretty much everything else
JavaScript - Chapter 4 - Types and StatementsWebStackAcademy
A computer program is a list of "instructions" to be "executed" by a computer.
In a programming language, these programming instructions are called statements.
A JavaScript program is a list of programming statements.
JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.
This statement tells the browser to write "Hello Dolly." inside an HTML element with id="demo":
JavaScript Data Types
JavaScript variables can hold many data types: numbers, strings, objects and more.
In programming, data types is an important concept.
To be able to operate on variables, it is important to know something about the type.
What is the DOM?
The DOM is a W3C (World Wide Web Consortium) standard.
The DOM defines a standard for accessing documents:
"The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document."
The W3C DOM standard is separated into 3 different parts:
Core DOM - standard model for all document types
XML DOM - standard model for XML documents
HTML DOM - standard model for HTML documents
The HTML DOM (Document Object Model)
When a web page is loaded, the browser creates a Document Object Model of the page.
The HTML DOM model is constructed as a tree of Objects.
With the HTML DOM, JavaScript can access and change all the elements of an HTML document.
Slide ini merupakan tutorial dasar dari penggunaan javaScript. Bagaimana javascript berjalan dan penggunaannya, javaScript statement, javaScript variable, javaScript looping, dan javaScript operator.
JSON stands for JavaScript Object Notation. JSON objects are used for transferring data between server and client.
JSON Is Not XML.
JSON is a simple, common representation of data.
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.
Les Hazlewood, Stormpath co-founder and CTO and the Apache Shiro PMC Chair demonstrates how to design a beautiful REST + JSON API. Includes the principles of RESTful design, how REST differs from XML, tips for increasing adoption of your API, and security concerns.
Presentation video: https://www.youtube.com/watch?v=5WXYw4J4QOU
More info: http://www.stormpath.com/blog/designing-rest-json-apis
Further reading: http://www.stormpath.com/blog
Sign up for Stormpath: https://api.stormpath.com/register
Stormpath is a user management and authentication service for developers. By offloading user management and authentication to Stormpath, developers can bring applications to market faster, reduce development costs, and protect their users. Easy and secure, the flexible cloud service can manage millions of users with a scalable pricing model.
This slide show is from my presentation on what JSON and REST are. It aims to provide a number of talking points by comparing apples and oranges (JSON vs. XML and REST vs. web services).
Some slides to talk about Preprocessors CSS, SASS in details
Twitter acount chagend: twitter.com/gBaylaender
Codepen acocunt changed: https://codepen.io/gbaylaender/pen/gIsnw
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
Guest college Webtechnology, Avans Breda, 2012.
An introduction to AJAX and JSON using jQuery.
Slides might not mean much on their own, but do provide working samples for further use.
This presentation deals with every possible topics under JSON (JavaScript Object Notation) which every web developers should know.
It is presented by Rajasekhar who works at United Online as a Web Developer
This presentation is meant to explain the JSON languages and the support that you need when this type of documents are edited, validated, queried, or converted. You will also discover what languages and tools can be used when working with these types of documents.
JSON it is a common format for data interchange and is adopted by applications as a way to store data. It is a self describing languages, the structure is defined hierarchically, and has schema to define its structure.
A JSON Schema can be used the define JSON documents structure. It is an Internet Draft at the IETF and not many tools support it, but it is actively developed.
Presentation on various definitions for JSON including JSON-RPC, JSPON, JSON Schema, JSONP and tools for working these definitions including Persevere client and server..
Free Downloadable PDF guide Volume #2 Learn to code JavaScript #javascript
A closure in JavaScript is a function that has access to variables in its parent scope, even after the parent function has returned. Closures are created when a function is defined inside another function, and the inner function retains access to the variables in the outer function’s scope.
Here is an example of a closure in JavaScript:In this example, the innerFunction is a closure because it has access to the variable x and innerVar from the outerFunction even after outerFunction has returned.
A closure has three scope chains:
It has access to its own scope (variables defined between its curly braces {}).
It has access to the outer function’s variables.
It has access to the global variables.
Closures are commonly used in JavaScript for a variety of tasks, such as:
Implementing private methods and variables.
Creating callback functions that retain access to variables from their parent scope.
Creating and returning an object that has access to variables from its parent scope.
JavaScript closures are an important concept and it is important to understand how closures work in JavaScript. It is also important to be aware of the scope chain, and how closures interact with the scope chain.JavaScript Object Notation (JSON) is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition – December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.
Some features that make it well-suited for data transfer:
It's simultaneously human- and machine-readable format;
It has support for Unicode, allowing almost any information in any human language to be communicated;
The self-documenting format that describes structure and field names as well as specific values;
The strict syntax and parsing requirements that allow the necessary parsing algorithms to remain simple, efficient, and consistent;
The ability to represent the most general computer science data structures: records, lists and trees.
JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa). You'll come across it quite often, so in this article, we give you all you need to work with JSON using JavaScript, including parsing JSON so you can access data within it, and create JSON.
We have presented an approach and shared experiences in using Facebook for teaching and learning. It has been shown that many students quickly respond to teachers’ posts and they also shared useful information. We have also evaluated and analyzed the result of the survey. It was found out that most people agree that the advantages are convenience, easy to use, and instance interaction while most people view the only disadvantages is too open to public
Educating the Net Generation
The Need for Using Facebook
The Need for Using Google Docs
How to Use Facebook for Teaching
How to Use Google Docs for Sharing and Collaborating
Experiences and Results
Conclusion
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfPaige Cruz
Monitoring and observability aren’t traditionally found in software curriculums and many of us cobble this knowledge together from whatever vendor or ecosystem we were first introduced to and whatever is a part of your current company’s observability stack.
While the dev and ops silo continues to crumble….many organizations still relegate monitoring & observability as the purview of ops, infra and SRE teams. This is a mistake - achieving a highly observable system requires collaboration up and down the stack.
I, a former op, would like to extend an invitation to all application developers to join the observability party will share these foundational concepts to build on:
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfPeter Spielvogel
Building better applications for business users with SAP Fiori.
• What is SAP Fiori and why it matters to you
• How a better user experience drives measurable business benefits
• How to get started with SAP Fiori today
• How SAP Fiori elements accelerates application development
• How SAP Build Code includes SAP Fiori tools and other generative artificial intelligence capabilities
• How SAP Fiori paves the way for using AI in SAP apps
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™UiPathCommunity
In questo evento online gratuito, organizzato dalla Community Italiana di UiPath, potrai esplorare le nuove funzionalità di Autopilot, il tool che integra l'Intelligenza Artificiale nei processi di sviluppo e utilizzo delle Automazioni.
📕 Vedremo insieme alcuni esempi dell'utilizzo di Autopilot in diversi tool della Suite UiPath:
Autopilot per Studio Web
Autopilot per Studio
Autopilot per Apps
Clipboard AI
GenAI applicata alla Document Understanding
👨🏫👨💻 Speakers:
Stefano Negro, UiPath MVPx3, RPA Tech Lead @ BSP Consultant
Flavio Martinelli, UiPath MVP 2023, Technical Account Manager @UiPath
Andrei Tasca, RPA Solutions Team Lead @NTT Data
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
PHP Frameworks: I want to break free (IPC Berlin 2024)Ralf Eggert
In this presentation, we examine the challenges and limitations of relying too heavily on PHP frameworks in web development. We discuss the history of PHP and its frameworks to understand how this dependence has evolved. The focus will be on providing concrete tips and strategies to reduce reliance on these frameworks, based on real-world examples and practical considerations. The goal is to equip developers with the skills and knowledge to create more flexible and future-proof web applications. We'll explore the importance of maintaining autonomy in a rapidly changing tech landscape and how to make informed decisions in PHP development.
This talk is aimed at encouraging a more independent approach to using PHP frameworks, moving towards a more flexible and future-proof approach to PHP development.
Elevating Tactical DDD Patterns Through Object CalisthenicsDorra BARTAGUIZ
After immersing yourself in the blue book and its red counterpart, attending DDD-focused conferences, and applying tactical patterns, you're left with a crucial question: How do I ensure my design is effective? Tactical patterns within Domain-Driven Design (DDD) serve as guiding principles for creating clear and manageable domain models. However, achieving success with these patterns requires additional guidance. Interestingly, we've observed that a set of constraints initially designed for training purposes remarkably aligns with effective pattern implementation, offering a more ‘mechanical’ approach. Let's explore together how Object Calisthenics can elevate the design of your tactical DDD patterns, offering concrete help for those venturing into DDD for the first time!
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionAggregage
Join Maher Hanafi, VP of Engineering at Betterworks, in this new session where he'll share a practical framework to transform Gen AI prototypes into impactful products! He'll delve into the complexities of data collection and management, model selection and optimization, and ensuring security, scalability, and responsible use.
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
3. What is JSON?
• JSON (JavaScript Object Notation) is a lightweight
data-interchange format. It is easy for humans to
read and write
• It is easy for machines to parse and generate.
• JSON is a text format that is completely language
independent
• JSON is built on two structures:
A collection of name/value pairs. In various languages, this
is realized as an object, record, struct, dictionary, hash
table, keyed list, or associative array.
o An ordered list of values. In most languages, this is
realized as an array, vector, list, or sequence.
o
4. JSON Forms: An object
• An object is an unordered set of name/value pairs
• An object begins with { (left brace) and ends
with } (right brace)
• Each name is followed by: (colon) and the name/
value pairs are separated by , (comma)
5. JSON Forms: An Array
• An array is an ordered collection of values
• An array begins with [ (left bracket) and ends with ] (right
bracket)
• Values are separated by , (comma).
6. JSON Forms: A Value
• A value can be a string in double quotes, or a number,
or true or false or null, or an object or an array
• These structures can be nested.
7. JSON Forms: A String
• A string is a sequence of zero or more Unicode characters, wrapped
in double quotes, using backslash escapes
• A character is represented as a single character string
• A string is very much like a C or Java string
8. JSON Forms: A Number
• A number is very much like a C or Java number, except that the
octal and hexadecimal formats are not used
11. Squiggles, Squares, Colons, and Commas
1. Squiggly brackets act as 'containers'
o {...}
• 2. Square brackets holds arrays
o [...]
• 3. Names and values are separated by a colon
o name:value
• 4. Array elements are separated by commas
o [member1, member2]
12. JSON is like XML because
1. They are both 'self-describing' meaning that values
are named, and thus 'human readable'
2. Both are hierarchical. (i.e. You can have values
within values.)
3. Both can be parsed and used by lots of programming
languages
4. Both can be passed around using AJAX (i.e.
httpWebRequest)
13. JSON is Unlike XML because
1. XML uses angle brackets, with a tag name at the start
and end of an element: JSON uses squiggly brackets
with the name only at the beginning of the element.
2. JSON is less verbose so it's definitely quicker for humans
to write, and probably quicker for us to read.
3. JSON can be parsed trivially using the eval() procedure
in JavaScript
4. JSON includes arrays {where each element doesn't have
a name of its own}
5. In XML you can use any name you want for an element,
in JSON you can't use reserved words from javascript
14. JSON in JavaScript
• JSON is a subset of the object literal notation of JavaScript.
Since JSON is a subset of JavaScript, it can be used in the
language with no muss or fuss.
• var myJSONObject =
{"bindings":
[ {"ircEvent": "PRIVMSG", "method": "newURI", "regex":
"^http://.*"}, {"ircEvent": "PRIVMSG", "method": "deleteURI",
"regex": "^delete.*"}, {"ircEvent": "PRIVMSG", "method":
"randomURI", "regex": "^random.*"} ] };
• In this example, an object is created containing a single
member "bindings", which contains an array containing three
objects, each containing "ircEvent", "method",
and"regex" members.
15. Accessing JSON in JavaScript
• var
myJSONObject
=
{"bindings":
[
{"ircEvent":
"PRIVMSG",
"method":
"newURI",
"regex":
"^h"p://.*"},...]}
• Members
can
be
retrieved
using
dot
or
subscript
operators.
myJSONObject.bindings[0].method
//
"newURI"
• To
convert
a
JSON
text
into
an
object,
you
can
use
the
eval()func[on.
eval()
invokes
the
JavaScript
compiler
• The
text
must
be
wrapped
in
parenthese
to
avoid
tripping
on
an
ambiguity
in
JavaScript's
syntax.
var
myObject
=
eval('('
+
myJSONtext
+
')');
16. Objects as Data
<html>
<body>
<script type="text/javascript">
var myFirstJSON = {"firstName" : "Tata",
"lastName" : "Saikaew",
"age" : 3};
document.writeln(myFirstJSON.firstName);
document.writeln(myFirstJSON.lastName);
document.writeln(myFirstJSON.age);
</script>
</body>
</html>
17. Nested Objects
<html>
<body>
<script type="text/javascript">
var employees = { "accountings" : [ // accounting is an array in
employees
{"firstName" : "Tata", "lastName" : "Saikaew", "age" : 30},
{"firstName" : "Teetee", "lastName" : "Wongkaew", "age" : 26} ],
"sales" : [ // Sales is another array in employees
{ "firstName" : "Manee", "lastName" : "Jaidee", "age" : 28},
{ "firstName" : "Mana", "lastName" : "Deejai", "age" : 32}]
}; // End employees
document.write(employees.accountings[0].firstName);
</script>
</body>
</html>
19. XML File
<wclass>
<!--My students who took web programming class with me-->
<student id="1">
<name>Linda Jones</name>
<legacySkill>Access, VB5.0</legacySkill>
</student>
<student id="2">
<name>Adam Davidson</name>
<legacySkill>Cobol, MainFrame</legacySkill>
</student>
<student id="3">
<name>Charles Boyer</name>
<legacySkill>HTML, Photoshop</legacySkill>
</student>
</wclass>
20. AJAX and XML Code (1/4)
<html>
<head>
<title>AJAX and XML</title>
<script language="javascript">
var xhr = false;
function GetXmlHttpObject(){
var xmlHttp=null;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
} catch (e) {
// Internet Explorer
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
21. AJAX and XML Code (2/4)
function getPage (url) {
xhr = GetXmlHttpObject();
if (!xhr) {
alert ('XMLHttp failed to instantiate');
return false;
}
xhr.onreadystatechange = statusCheck;
xhr.open ('GET', url, true);
xhr.send (null);
}
22. AJAX and XML Code (3/4)
function statusCheck() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var nodes=xhr.responseXML.getElementsByTagName("student");
j = 1;
for (i=0; i<nodes.length; i++) {
var student = nodes.item(i);
document.getElementById(j++).innerHTML= (i+1) + ". Student
name:" +
student.firstChild.nextSibling.firstChild.nodeValue + " skill:" +
student.lastChild.previousSibling.firstChild.nodeValue;
}
} else {
alert ('The request could not be fulfilled.');
}
}
}
</script>
23. AJAX and XML Code (4/4)
</head>
<body>
<input id=button2 onclick=
"getPage ('http:///localhost/~Macbook/json/
webstudents.xml')" type=button
value="Get the XML Document" name=button2>
<br/>
<div id=1></div></p>
<div id=2></div></p>
<div id=3></div></p>
</body>
</html>
28. Using JSON in the Google Data Protocol
• The feed is represented as a JSON object; each
nested element or attribute is represented as a
name/value property of the object.
• Attributes are converted to String properties.
• Child elements are converted to Object properties.
• Elements that may appear more than once are
converted to Array properties.
• Text values of tags are converted to $t properties#
30. Requesting and Using JSON Feeds
• Atom is Google Data's default format. If you don't
specify an alt parameter in your request, then you
receive an Atom feed
• To request a response in JSON format, use
the alt=json parameter.
• For example, to request Google's developer
calendar feed in JSON format, send the following
query:
• http://www.google.com/calendar/feeds/developercalendar@google.com/public/full?alt=json
31. Getting JSON Feeds in Javascript
• To request a response that wraps JSON in a script
tag, use the alt=json-in-script parameter and add a
callback function by adding
the callback=functionName parameter.
• http://www.google.com/calendar/feeds/developercalendar@google.com/public/full?alt=json-inscript&callback=myFunction
32. Sample Script to Get JSON Feeds (1/2)
<h3>Upcoming Google Developer Events</h3>
<div id="agenda"></div>
<script>
function listEvents(root) {
var feed = root.feed;
var entries = feed.entry || [];
var html = ['<ul>'];
for (var i = 0; i < entries.length; ++i) {
var entry = entries[i];
var title = entry.title.$t;
var start = (entry['gd$when']) ? entry['gd$when']
[0].startTime : ""; html.push('<li>', start, ' ', title, '</li>'); }
33. Sample Script to Get JSON Feeds (2/2)
html.push('</ul>');
document.getElementById("agenda").innerHTML =
html.join(""); }
</script>
<script src="http://www.google.com/calendar/feeds/
developer-calendar@google.com/public/full?alt=jsonin-script&callback=listEvents">
</script>
38. Encode Class to JSON in PHP (1/2)
<?php
class
User
{
public
$firstname
=
"";
public
$lastname
=
"";
public
$birthdate
=
"";
}
$user
=
new
User();
$user-‐>firstname
=
"foo";
$user-‐>lastname
=
"bar";
json_encode($user);
$user-‐>birthdate
=
new
DateTime();
echo
json_encode($user);
?>
38
39. Encode Class to JSON in PHP (2/2)
<?php
class
User
{
public
$pub
=
"Mister
X.";
protected
$pro
=
"hidden";
private
$priv
=
"hidden
too”;
public
$func;
public
$notUsed;
public
func[on
__construct()
{
$this-‐>func
=
func[on()
{
return
"Foo";
};
}
}
$user
=
new
User();
//
Returns:
{"pub":"Mister
X.","func":{},"notUsed":null}
echo
json_encode($user);
?>
39
40. The $option bitmask
Without
bitmask
•
echo
json_encode(array("Starsky
&
Hutch",
"123456"));
With
bitmask
• echo
json_encode(array("Starsky
&
Hutch",
"123456"),
JSON_NUMERIC_CHECK
|
JSON_FORCE_OBJECT);
40
42. Encoding Data in UTF-8
• If
the
incoming
string
is
not
under
your
control,
you
can
use
the
uz8_encode
func[on
to
convert
it
into
uz8
<?php
$payload
=
array("กานดา
รุณนะพงศา
สายแก้ว");
echo
uz8_encode(json_encode($payload,
JSON_FORCE_OBJECT));
?>
42
44. Decode JSON in PHP (2/3)
• If you want to get an associative array back instead, set
the second parameter to true:
<?php
$string = '{"foo": "bar", "cool": "attr"}';
$result = json_decode($string, true);
// Result: array(2) { ["foo"]=> string(3) "bar" ["cool"]=> string(4) "attr" }
var_dump($result);
// Prints "bar"
echo $result['foo'];
echo "<br/>";
// Prints "attr"
echo $result['cool'];
?>
44
45. Decode JSON in PHP (3/3)
• If
you
expect
a
very
large
nested
JSON
document,
you
can
limit
the
recursion
depth
to
a
certain
level
• The
func[on
will
return
null
and
stops
parsing
if
the
document
is
deeper
than
the
given
depth
45