Do I need to use XML files with Ajax, as the name suggests? Or can I use any file format?
Although XML is used to make the name Ajax, it is an option and not a necessity and we can also use files in text format, and therefore files in JSON format which is textual and provides a simplified alternative to XML.
The term Ajax, shortcut for Asynchronous JavaScript + XML, the XML mention is here as a possibility.
When launching the Ajax request, the object created as an instance of XMLHttpRequest has two attributes that are assigned with the server's response:
1. responseText containing a text document. 2. responseXML containing an XML document whose tags can be accessed thought DOM.
responseText may contain a JSON file, which represents the data more concisely than XML and has the advantage of being directly usable by JavaScript, because it is similar to the definition of an array. But it must be evaluated by JavaScript to be assigned to a variable.
The code will have this form:
function demo () { if (req.readyState == 4) { var x = eval ( '(' + req.responseText +')'); } }
The x variable contains an array filled with the data from the JSON file.
More information on the use of JSON is available in the link resource. HTML files can not be returned by the server but as text files.
JSON Tutorial Introduction to this simple file format.
Why not responseHTML? A method to overcome a limitation in XMLHttpRequest.