-
Data formats
-
Your choices
-
XML
The X in AJAX
- Returned in the
responseXML
property
- The server must send the correct header e.g. text/xml
- Can be traversed and manipulated using DOM methods (e.g
getElementsByTagName
) and properties (e.g. childNode
, nodeValue
, etc.)
- Examples:
People profiles
(data)
(JS),
RSS reader
(data)
(JS)
-
Advantages of XML
-
Disadvantages of XML
- Requires a lot of finicky client-side DOM manipulation
- Slow
-
HTML
-
Advantages of HTML
- Very little client-side processing
- Fast
- The server can send one output format, whether the request comes from Ajax or not
-
Disdvantages of HTML
- Uses the brute force of the proprietary
innerHTML
property
- Won't work on XHTML served with the correct mime-type in Firefox 1.0
- Not very useful for changing a document in more than one place
-
JSON
- Proposed by Douglas Crockford. A nested list of name/value pairs described using JavaScript's object syntax.
- Can be returned in the
resonseText
property.
- Could also be requested without using
XMLHttpRequest
!
- Use the DOM to change the
src
attribute of a <script>
tag, pointing it to a resource that returns JSON. Then eval()
the returned JavaScript.
- Examples:
People profiles
(data)
(JS),
RSS reader
(data)
(JS)
-
Examples of JSON
Using JSON with a web service from a different site.
-
Advantages of JSON
- Lightweight
- Some APIS will return JSON (e.g. Yahoo!)
- Can get around the same-site restriction
-
Disadvantages of JSON
- Not as readable as XML or HTML
- Potential problems with character encoding and escaping quotes
- Uses
eval()
so the source must be trustworthy
-
Which format to choose
Choose the best format for the job.
- To update many different parts of the current document, XML may be best.
- To retrieve data directly from another server, JSON (and the
<script>
tag hack) is the only option.
- To update one part of the page, just use
innerHTML
to insert a fragment of HTML
-
Next
Doing the right thing: Hijax