Temas > Programacion > Java script - Java > JSON en jQuery
Julio

$.getJSON
La función getJSON hace una petición de datos al servidor 
considerando que retorna la información con notación JSON. 
La sintaxis de esta función es:
$.getJSON([nombre de la página], [parámetros], [función que recibe 
los datos])
La función getJSON procede a generar un objeto en JavaScript y 
nosotros en la función lo procesamos.
       1.El usuario hace click en un link para obtener datos.
       2.JavaScript llama a un fichero PHP enviándole algunos
parámetros.
       3.El fichero PHP recibe los parámetros y devuelve los datos.
       4.JavaScript recibe los datos y los muestra como HTML.
pagina1.html
<?php //esto no va
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 <html xml:lang="en" lang="en" xmlns="http://www.w3.org/
1999/xhtml">
 <head>
 <title>Table row hovers with jQuery example - adeepersilence.be</title>
 <meta http-equiv="content-type" content="text/html; 
charset=iso-8859-15" />
 <meta http-equiv="content-language" content="en" />
 <style type="text/css">
               body {
                       margin: 50px 0 0 100px;
               }
               p {
                       font-size: 0.8em;
                       padding: 20px 0 0 0;
               }
 </style>
 <script type="text/javascript" src="../jquery.js"></script>
 <script type="text/javascript" src="funciones.js"></script>
 </head>
 <body>
 <ul id="mylist">
        <li><a rel="3" href="#dave">Dave`s email</a></li>
        <li><a rel="4" href="#erik">Erik`s email</a></li>
 </ul>
 <p id="info">&nbsp;</p>
 </body>
 </html>
?>//esto no va
funciones.js
<?php //esto no va
 $(`document`).ready(function(){
 // an anchor element in the list `mylist` gets clicked
               $(`#mylist a`).click(function (){
 // the ID of the record we need to retrieve is stored in the rel element,

so we fetch it first
               var id = $(this).attr(`rel`);
 // do the JSON call to getinfo.php, send the ID parameter with it and 
allback to parseEmail
               $.getJSON(`getinfo.php`, {`id` : id}, parseInfo);
               });
        });
 // this function parses the fetched data into the `info` paragraph
        function parseInfo(data){
 // the data parameter is an object, while name and email are the keys 
from the PHP array
 // you can also use the `text` function instead of html. The difference 
is that `text`
 // displays raw text, even if it contains other HTML elements.
               $(`#info`).html(data.name +`, `+ data.email);
        }
?>//esto no va
getinfo.php

 <?php
 // see if we have a GET variable `id` set
 $id = (isset($_GET[`id`]) && !empty($_GET[`id`])) ? $_GET[`id`] : 0;
 // pretend this is a query to a database to fetch the wanted users.
 $users[3] = array(`name` => `Dave`, `email` => `dave@adeepersilence.be`);
 $users[4] = array(`name` => `Erik`, `email` => `erik@bauffman.be`);
 // only if an ID was given and the key exists in the array, we continue
 if(!empty($id) && key_exists($id, $users))
 {
        // echo (not return) the wanted record from the users array
        echo json_encode($users[$id]);
 }
 ?>

Cuando se hace click sobre cualquiera de los enlaces procedemos 
a realizar la petición asincrónica utilizando la función getJSON:
<?php //esto no va
$(`#mylist a`).click(function ()
{
        var id = $(this).attr(`rel`);
        $.getJSON(`getinfo.php`, {`id` : id}, parseInfo);
});
?>//esto no va
Como hemos llamado a la función getJSON la misma nos retorna 
un objeto JavaScript para procesarlo:
<?php //esto no va
function parseInfo(data)
{
        $(`#info`).html(data.name +`, `+ data.email);
}
?>//esto no va
Donde `data` es el objeto que devuelve getJSON.
Tengamos en cuenta que el programa en el servidor debe 
retornar un archivo con notación JSON:
<?php
$id = (isset($_GET[`id`]) && !empty($_GET[`id`])) ? $_GET[`id`] : 0;
$users[3] = array(`name` => `Dave`, `email` => `dave@adeepersilence.be`);
$users[4] = array(`name` => `Erik`, `email` => `erik@bauffman.be`);
if(!empty($id) && key_exists($id, $users))
{
        echo json_encode($users[$id]);
}
?>
[1] Note that you need PHP 5.2 or higher to use json_encode()
[2] The $.getJSON() method does an HTTP GET and not POST. You need to use
$.post()
$.post(url, dataToBeSent, function(data, textStatus) {
  //data contains the JSON object
  //textStatus contains the status: success, error, etc
}, "json");
In that call, dataToBeSent could be anything you want, although if are
sending the
contents of a an html form, you can use the serialize method to create the
data for
the POST from your form.
var dataToBeSent = $("form").serialize();













¿Has olviado tu contraseña?

Pulsa aquí para registrate




Google






LunMarMieJueVieSabDom
     12
3456789
10111213141516
1718192021 2223
24252627282930
31      

Sabado 22 de Marzo 2025
Semana 12



Java script - Java


-Input type submit con evento onclick
-Maneras de salir de un iframe con java script
-Sintaxis de un list array en java
-Consumir un JSON desde PHP
-Producir JSON desde PHP
-Mostrar un tooltip con datos recuperados en jQuery
-Menu desplegable en jQuery
-Llamadas encadenadas de metodos del objeto jQuery
-Funcion ajax en jQuery
-Pasando datos por los metodos GET y POST en jQuery
-Ajax metodos ajaxStart y ajaxStop en jQuery
-Ajax metodo load en jQuery
-Iteracion por los elementos each en jQuery
-Efecto con el metodo toggle en jQuery
-Efecto con el metodo fadeTo en jQuery
-Efectos con los metodos fadeIn y fadeOut en jQuery
-Efectos con los metodos show y hide en jQuery
-Manipulacion de los elementos del DOM en jQuery
-Evento blur en jQuery
-Evento focus en jQuery
-Evento dblclick en jQuery
-Eventos mousedown y mouseup en jQuery
-Evento mousemove en jQuery
-Evento hover en jQuery
-Eventos mouseover y mouseout en jQuery
-Administracion de eventos con jQuery
-Metodos html y html valor en jQuery
-Metodos addClass y removeClass en jQuery
-Metodos attr y removeAttr en jQuery
-Metodos text, text valor en jQuery
-Seleccion de elementos con la clase CSS definida
-Seleccion de elementos utilizando el selector CSS
-Seleccion de elementos por el tipo de elementos jQ
-Seleccion de un elemento mediante el id jQuery
-Nueva manera de programar JavaScript con jQuery
-Que es el jQuery
-Archivo JavaScript externo
-Propiedad screen del objeto window en java script
-Propiedad location de objeto window en java script
-El objeto window en java script
-Eventos onMouseOver y onMouseOut en java script
-Eventos onFocus y onBlur en java script
-Control TEXTAREA en java script
-Control RADIO en java script
-Control CHECKBOX en java script
-Control SELECT en java script
-Control PASSWORD en java script
-Controles FORM, BUTTON y TEXT en java script
-Formularios y Eventos en java script
-Clase Math en java script
-Clase String en java script
-Clase Array en java script
-Clase Date en java script
-Programacion orientada a objetos en java script
-Funciones que retornan un valor en java script
-Funciones con parametros en java script
-Funciones en java script
-Estructura repetitiva for en java script
-Estructura repetitiva do while en java script
-Concepto de acumulador en java script
-Estructura repetitiva (while) en java script
-Operadores logicos or en las estructuras java s
-Operadores logicos (and) en las estructuras java s
-Estructuras condicionales anidadas en java script
-Estructuras condicionales compuesta en jaca script
-Estructuras condicionales simples en java script
-Estructuras secuenciales en java script
-Entrada de datos por teclado en java script
-Variables en java script
-Que es JavaScript
-Lectura y escritura de archivos en java
-Entrada y salida estandar en Java
-Programa para contar vocales de un fichero en java
-Convertidor de divisas en java
-Form con una ventana nueva
-Seleccionar un elemento html mediante su id
..............................................................................................................................................................................................................................................
(Contacto)..
Esta web utiliza cookies para obtener datos estadísticos de la navegación de sus usuarios. Política de privacidad y Aviso legal