with json you can store data in a structured way after XML. Here's the same information contained inside the sample XML file earlier using Json syntax instead
Read The Full Tutorial.
with json you can store data in a structured way after XML. Here's the same information contained inside the sample XML file earlier using Json syntax instead
{ title: "javascriptkit.com", link: "http://www.javascriptkit.com", description: "JavaScript tutorials and over 400+ free scripts!", language: "en", items: [ { title: "Document Text Resizer", link: "http://www.javascriptkit.com/script/script2/doctextresizer.shtml", description: "This script adds the ability for your users to toggle your webpage's font size, with persistent cookies then used to remember the setting" }, { title: "JavaScript Reference- Keyboard/ Mouse Buttons Events", link: "http://www.javascriptkit.com/jsref/eventkeyboardmouse.shtml", description: "The latest update to our JS Reference takes a hard look at keyboard and mouse button events in JavaScript, including the unicode value of each key." }, { title: "Dynamically loading an external JavaScript or CSS file", link: "http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml", description: "External JavaScript or CSS files do not always have to be synchronously loaded as part of the page, but dynamically as well. In this tutorial, see how." } ]
}
JSON and XML files are both just plain text files. Unlike XML files, however, the browser currently doesn't provide a way to natively return a JSON file as a JavaScript object (unlike "request.responseXML" with XML for example). However, the use of eval() on "request.responseText" does the trick just fine, and is the key to using Ajax with JSON files:
<div id="result"> </div>
<script type="text/javascript">
function ajaxRequest(){ var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"] //activeX versions to check for in IE if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) for (var i=0; i<activexmodes.length; i++){ try{ return new ActiveXObject(activexmodes[i]) } catch(e){ //suppress error } } } else if (window.XMLHttpRequest) // if Mozilla, Safari etc return new XMLHttpRequest() else return false }
var mygetrequest=new ajaxRequest() mygetrequest.onreadystatechange=function(){ if (mygetrequest.readyState==4){ if (mygetrequest.status= 0 || window.location.href.indexOf("http")==-1){ var jsondata=eval("("+mygetrequest.responseText+")") //retrieve result as an JavaScript object var rssentries=jsondata.items var output='<ul>' for (var i=0; i<rssentries.length; i++){ output+='<li>' output+='<a href="'+rssentries[i].link+'">' output+=rssentries[i].title+'</a>' output+='</li>' } output+='</ul>' document.getElementById("result").innerHTML=output } else{ alert("An error has occured making the request") } } }
mygetrequest.open("GET", "javascriptkit.json", true) mygetrequest.send(null)
</script>
|