29 enero 2008

Usando JSON con PHP

JSON (JavaScript Object Notation) se puede utilizar en lugar de XML para el intercambio de información con Javascript. Algunos llaman AJAJ en lugar de AJAX a la programación Javascript asíncrona con JSON. La clave para leer objetos JSON con Javascript es la función eval() que debe ser utilizada con precaución, ya que ejecuta cualquier código que se le pase como parámetro.

Para intercambiar información JSON entre Javascript y PHP existen dos funciones muy útiles (a partir de PHP 5.x): json_encode() y json_decode().

Ejemplo:

$i = array(
array("id" => 1, "name" => "linus"),
array("id" => 2, "name" => "bill"),
array("id" => 3, "name" => "steve")
);

echo json_encode($i);

El resultado será:
[{"id":1,"name":"linus"},{"id":2,"name":"bill"},{"id":3,"name":"steve"}]

Para utilizar los datos JSON en el cliente mediante Javascript usaremos eval() para leer el objeto enviado desde PHP:
var json = eval('(' + miRespuestaJSON + ')');
for(var i = 0; i < json.length; i++)
{
console.info(json.id + " " + json.name);
}

Fuente:
http://www.json.es/2007/07/09/usando-json-desde-php/

1 comentario:

Simon Matthew dijo...

That's adorable! User testing jobs are so high in the market that it is difficult to shortlist the right company to choose for starting the career in the same. Freshers already struggle a lot, and the concern grows more when you are lost in choosing the right one from the crowd. That's; when the right approach serves you best.
I was also in the same situation, but I got Eiliana.com at my back, who supported me immensely to get the right one.