2009-08-05 11 views
9

tengo este código, y también han intentado algo similar usando la función $ .getJson:Usando jQuery para obtener datos JSON devuelve el error de etiqueta no válido

jQuery(document).ready(function(){ 
    var kiva_url = "http://api.kivaws.org/v1/loans/newest.json"; 

    jQuery.ajax({ 
     type: "GET", 
     url: kiva_url, 
      data:"format=json", 
     success: function(data){ 
      alert("here"); 
      jQuery.each(data.loans, function(i, loan){ 
       jQuery("#inner_div").append(loan.name + "<br />"); 
      }); 
     }, 
     dataType: "jsonp", 
     error: function(){ 
      alert("error"); 
     } 
    }); 

}); 

Cuando miro en Firebug se está volviendo una etiqueta de "no válido "error. He buscado un poco, algunas personas se refieren a usar un analizador para analizar los resultados. Puedo ver los resultados regresando en Firebug. ¿Alguien puede señalar un ejemplo de lo que debería estar haciendo? error

El Firebug:

invalid label http://api.kivaws.org/v1/loans/newest.json?callback=jsonp1249440194660&_=1249440194924&format=json& Line 1

Salida de ejemplo de lo que el JSON se ve como se puede encontrar aquí: http://build.kiva.org/docs/data/loans

Respuesta

5

Bueno he encontrado la respuesta ... parece que Kiva no soporta jsonp que es lo que se hace aquí jQuery -

http://groups.google.com/group/build-kiva/browse_thread/thread/9e9f9d5df821ff8c

...we don't have plans to support JSONP. Supporting this advocates poor security practices and there are already some good ways to access the data from JavaScript that protect your application and your users. Here's a great article on the subject:

http://yuiblog.com/blog/2007/04/10/json-and-browser-security/

While the risk to Kiva lenders is low now since we are only dealing with public data, allowing private lender data to be imported via script tags is a risk further down the road. Our thought is the risk (and complexity added to create secure applications) is not worth the benefit to developers.

Writing a server-side proxy for the feeds you need is the most common solution to accessing data in browser-based applications. Some other tricks exist using iFrames. The best hope is the new breed of client- based technologies/standards that will let browser-based JavaScript access cross-domain resources securely ( http://dev.w3.org/2006/waf/access-control/ http://json.org/JSONRequest.html ). Some tools like BrowserPlus and Gears let you play with these today, but you won't be able to depend on these in the wild for a while.

As a final note, I'll point out that anyone using JSON responses in JavaScript should either parse JSON explicitly or validate the JSON before taking eval() to it. See here:

http://www.JSON.org/js.html

Linked from the page is a great reference implementation of the proposed ECMAScript JSON parser interface, JSON.parse().

Cheers, skylar

+0

Gracias Brendan, ¡me acabas de ahorrar un montón de tiempo! – ezeedub

0

¿Dónde ocurre el error? ¿Se produce un error cuando intenta recorrer los datos de AJAX y anexarlo a inner_div? En caso afirmativo, muéstrenos cómo son los datos.

Además, hay un error tipográfico en el código:

  jQuery.each(data.loans, function(i, loan){ 
        jQuery("#inner_div").append(loan.name + "<br />"); //It should be loan.name and not laon.name 
      }); 
    }, 
+0

fijo mi error tipográfico - Creo que está en la retrieve- Si tomo a cabo ese bucle jQuery todavía consigo el error. – brendan

+0

¿qué línea da el error? ¿Puedes incluir una instantánea de error de Firebug? – SolutionYogi

+0

agregó la salida de la consola Firebug – brendan

2

Cuando devuelve los datos, ¿los devuelve con el tipo de contenido correcto y como método?

Debe devolver los datos de la siguiente manera (PHP 5 ejemplo):

$return = "my_callback_method(" . json_encode(array('data'=>'your data etc')). ")"; 

while (@ob_end_clean()); 
header('Cache-Control: no-cache'); 
header('Content-type: application/json'); 
print_r($return); 

En su llamado código javascript, debe tener un método para que coincida con el método de devolución de llamada que regresó, en este caso:

function my_callback_method(returned_data){ 
} 

lo tanto, sus js de llamadas completo debería ser algo como lo siguiente

jQuery(document).ready(function(){ 
var kiva_url = "http://api.kivaws.org/v1/loans/newest.json"; 

jQuery.ajax({ 
    type: "GET", 
    url: kiva_url, 
     data:"format=json", 
    dataType: "jsonp", 
    error: function(xmlhttp,error_msg){ 
      alert("error"+error_msg); 
    } 
}); 

function my_callback_method(data){ 
    alert("here"); 
    if(data && typeof(data) == 'object')){ 
    jQuery.each(data.loans, function(i, loan){ 
     jQuery("#inner_div").append(loan.name + "<br />"); 
    }); 
    } 
} 

}); 
0

Esta es la respuesta http://forum.jquery.com/topic/jquery-getjson-invalid-label

Simplemente ajuste su respuesta Json con su solicitud de devolución de llamada P. ej. jQuery16203473509402899789_1315368234762({"Code":200,"Message":"Place added successfully","Content":""}); donde jQuery16203473509402899789_1315368234762 es su petición de devolución de llamada (lo puede conseguir a través de la cadena de consulta) {"Code":200,"Message":"Place added successfully"} es su respuesta JSON

Cuestiones relacionadas