Foros del Web » Programando para Internet » Jquery »

No puedo acceder a objeto json luego de un callback jquery

Estas en el tema de No puedo acceder a objeto json luego de un callback jquery en el foro de Jquery en Foros del Web. Hola, tengo dos páginas: en index.php este formulario: @import url("http://static.forosdelweb.com/clientscript/vbulletin_css/geshi.css"); Código HTML: Ver original < form id = "formu" action = "#" >     ...
  #1 (permalink)  
Antiguo 01/02/2012, 13:06
Avatar de cristian_cena
Colaborador
 
Fecha de Ingreso: junio-2009
Mensajes: 2.244
Antigüedad: 14 años, 10 meses
Puntos: 269
No puedo acceder a objeto json luego de un callback jquery

Hola, tengo dos páginas:

en index.php este formulario:
Código HTML:
Ver original
  1. <form id="formu" action="#">
  2.     <input id="domain" type="text" name="whois" class="input">
  3.     <input type="submit" value="buscar" />
  4. </form>
cuyo submit es procesado por este script:
Código Javascript:
Ver original
  1. $(function(){
  2.     $("#formu").submit(function(event){
  3.         event.preventDefault();        
  4.         $.post("procesa_index.php", $("#formu").serialize(), function(data){
  5.             console.log(data.domain); //acá el problema
  6.         });    
  7.     });
  8. });
en procesa_index.php:
Código PHP:
Ver original
  1. /* arriba trabajo con una clase y finalmente los valores los guardo en un array al que luego lo paso a formato json y lo imprimo*/
  2. $data = array(
  3.     "domain" => $domain,
  4.     "result" => $result,
  5.     "server" => $server,
  6.     "debug"  => $debug,
  7.     "errors" => $errors,
  8.     "output" => $output
  9. );
  10. echo json_encode($data);
lo que genera por ejemplo el siguiente json:

Código Javascript:
Ver original
  1. {
  2.    "domain":"ejemplo.com",
  3.    "result":"registered",
  4.    "server":"whois.verisign-grs.com",
  5.    "debug":"Used trigger: 'Domain Name:'",
  6.    "errors":"",
  7.    "output":"\nWhois Server Version 2.0\n\nDomain names in the .com and .net domains can now be registered\nwith many different competing registrars. Go to http:\/\/www.internic.net\nfor detailed information.\n\n   Domain Name: EJEMPLO.COM\n   Registrar: FABULOUS.COM PTY LTD.\n   Whois Server: whois.fabulous.com\n   Referral URL: http:\/\/www.fabulous.com\n   Name Server: NS1.FABULOUS.COM\n   Name Server: NS2.FABULOUS.COM\n   Status: clientDeleteProhibited\n   Status: clientTransferProhibited\n   Updated Date: 10-dec-2010\n   Creation Date: 07-jun-2001\n   Expiration Date: 07-jun-2012\n\n&gt;&gt;&gt; Last update of whois database: Wed, 01 Feb 2012 18:50:11 UTC &lt;&lt;&lt;\n\nNOTICE: The expiration date displayed in this record is the date the \nregistrar's sponsorship of the domain name registration in the registry is \ncurrently set to expire. This date does not necessarily reflect the expiration \ndate of the domain name registrant's agreement with the sponsoring \nregistrar.  Users may consult the sponsoring registrar's Whois database to \nview the registrar's reported date of expiration for this registration.\n\nTERMS OF USE: You are not authorized to access or query our Whois \ndatabase through the use of electronic processes that are high-volume and \nautomated except as reasonably necessary to register domain names or \nmodify existing registrations; the Data in VeriSign Global Registry \nServices' (&quot;VeriSign&quot;) Whois database is provided by VeriSign for \ninformation purposes only, and to assist persons in obtaining information \nabout or related to a domain name registration record. VeriSign does not \nguarantee its accuracy. By submitting a Whois query, you agree to abide \nby the following terms of use: You agree that you may use this Data only \nfor lawful purposes and that under no circumstances will you use this Data \nto: (1) allow, enable, or otherwise support the transmission of mass \nunsolicited, commercial advertising or solicitations via e-mail, telephone, \nor facsimile; or (2) enable high volume, automated, electronic processes \nthat apply to VeriSign (or its computer systems). The compilation, \nrepackaging, dissemination or other use of this Data is expressly \nprohibited without the prior written consent of VeriSign. You agree not to \nuse electronic processes that are automated and high-volume to access or \nquery the Whois database except as reasonably necessary to register \ndomain names or modify existing registrations. VeriSign reserves the right \nto restrict your access to the Whois database in its sole discretion to ensure \noperational stability.  VeriSign may restrict or terminate your access to the \nWhois database for failure to abide by these terms of use. VeriSign \nreserves the right to modify these terms at any time. \n\nThe Registry database contains ONLY .COM, .NET, .EDU domains and\nRegistrars."
  8. }

El problema lo tengo en la línea nº 5 del script jquery (arriba) donde hago un "console.log()" y paso como parámetro data.domain.
En lugar de obtener la salida "ejemplo.com" obtengo "undefined"
¿estoy accediendo mal al objeto?

Desde ya muchas gracias por su respuesta.
  #2 (permalink)  
Antiguo 01/02/2012, 14:30
Avatar de maycolalvarez
Colaborador
 
Fecha de Ingreso: julio-2008
Ubicación: Caracas
Mensajes: 12.120
Antigüedad: 15 años, 8 meses
Puntos: 1532
Respuesta: No puedo acceder a objeto json luego de un callback jquery

eso es porque en ningún momento le dijiste a jQuery que la respuesta viene en formato json, debes asignarlo con dataType: 'json'

por defecto jQuery lo reconoce, pero si la respuesta tiene el encabezado adecuado, en tu caso con agregar un header('Content-type: application/json'); o text/json, pero es más seguro especificarlo desde jQuery
__________________
¡Por favor!: usa el highlight para mostrar código
El que busca, encuentra...
  #3 (permalink)  
Antiguo 01/02/2012, 15:43
Avatar de cristian_cena
Colaborador
 
Fecha de Ingreso: junio-2009
Mensajes: 2.244
Antigüedad: 14 años, 10 meses
Puntos: 269
Respuesta: No puedo acceder a objeto json luego de un callback jquery

Hola maycol, muchisimas gracias.
Incluí en procesa_index.php:
header('Content-type: application/json');
y funcionó a la perfección.

Saludos.

Etiquetas: ajax, callback, data, json, php
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 07:47.