Friday, October 14, 2011

Example: JSON

WARNING!! Do not test it in Chrome it will not work. Only live.

JSON: is used for data storage and can be an alternative to XML.

HTML:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

<script>
window.onerror = function(a,b,c){alert(a+b+c);} //if error alert
$(document).ready(function(){
//Short hand
$('button').click(function(){
$.getJSON("info.js", function(json) {
alert(json.name[1].first)
});

//Long
$.ajax({
async: false,
url: 'info.js',
dataType:'json',
success: function(json) {
ret = json.name[1].first;
}
});
});
});
</script>

<p>hello</p>
<button>Click Me</button>

JSON (info.js) - everything must have double quotes except numbers. You cannot comment in JSON. It has to look like the example below and it has to be in object/brackets {}

{
"name" : [{"first" : "Britney", "last":"Spears"},
{"first" : "Angelina", "last":"Jolie"}],
"age" : 25
}

No comments:

Post a Comment