Wednesday, 5 September 2007

AJAX & Web 2.0 Tutorial (Section 3) - JSON




  1. JSON (JavaScript Object Notation) is a subset of how objects are represented in JavaScript
  2. It’s presented as a lightweight information transfer protocol, similar in many respects to XML
  3. What makes JSON useful in JavaScript is that it can be parsed very easily (eval())JSON can contain any number of elements, nested key value pairs, objects, arrays, etc.
  4. Until a library is introduced the easiest way to transfer data between your script and PHP is to use simple GET & POST based requests for transmission, and JSON for receipt.
  5. Different browsers interpret JavaScript differently, IE in particular goes off in its own direction (xmlHTTP request works differently, it’s difficult to re-use ajax objects, data is stored in linked lists rather than a hash table so it’s notably slower)
  6. You could do some serious research, understand all the little differences, and write your code appropriately, or...


JSON Example:

<script type="text/javascript">
var name = "alex";
httpRequest = new XMLHttpRequest();
httpRequest.open('GET', 'http://localtest.luxplus.net/alfa/
ucase.php?text=' + name);
httpRequest.onreadystatechange = function()
{
if (httpRequest.readyState == 4)
{
responseJSON = eval("(" + httpRequest.responseText + ")");
alert(responseJSON.ucase);
}
}
httpRequest.send(null);
</script>


/* ucase.php */

<?php
$string = isset($_GET['text']) ? strtoupper($_GET['text']) :
strtoupper("default");
$data['ucase'] = $string;
$returnValue = json_encode($data);
echo $returnValue;
?>


1 comment:

startoy said...

there is also a large and comprehensive database of 800+ ajax scripts available with over at ajaxflakes’s ajax scripts compound

thought i should add it might be helpful to others…

here