2009-08-05 4 views
9

J'ai ce code, et ont également essayé quelque chose de similaire en utilisant la fonction .getJson $:En utilisant jQuery pour obtenir des données JSON renvoie l'erreur d'étiquette invalide

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"); 
     } 
    }); 

}); 

Quand je regarde dans Firebug, il retourne une « étiquette invalide " Erreur. J'ai cherché un peu autour de quelques personnes se réfèrent à l'aide d'un analyseur pour analyser les résultats. Je peux voir les résultats revenir dans Firebug. Quelqu'un peut-il montrer un exemple de ce que je devrais faire?

L'erreur Firebug:

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

sortie de l'échantillon de ce que le JSON ressemble peut être trouvé ici: http://build.kiva.org/docs/data/loans

Répondre

5

Eh bien, je trouve la réponse ... il semble que Kiva ne supporte pas jsonp qui est ce que jquery fait ici -

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

Merci Brendan, vous venez de me sauver un tas de temps! – ezeedub

0

Où l'erreur se produit-elle? Une erreur se produit-elle lorsque vous essayez de faire défiler les données ajax et de les ajouter à inner_div? Si oui, veuillez nous montrer à quoi ressemblent les data.loans.

En outre, il y a une faute de frappe dans votre code:

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

fixe ma faute de frappe - je crois qu'il est sur le retrieve- Si je prends cette boucle jquery je reçois toujours l'erreur. – brendan

+0

quelle ligne donne l'erreur? Pouvez-vous inclure un instantané d'erreur Firebug? – SolutionYogi

+0

ajouté sortie console firebug – brendan

2

Lorsque vous renvoyez les données, les renvoyez-vous avec le bon type de contenu et comme méthode?

Vous devez retourner vos données comme suit (php 5 exemple):

$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); 

Dans votre appel code javascript, vous devez avoir une méthode pour correspondre à la méthode de rappel à votre retour, dans ce cas:

function my_callback_method(returned_data){ 
} 

Ainsi, vos js d'appel complet devrait ressembler à quelque chose comme ce qui suit

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

C'est la réponse http://forum.jquery.com/topic/jquery-getjson-invalid-label

Enveloppez simplement votre réponse Json avec votre demande de rappel Par ex. jQuery16203473509402899789_1315368234762({"Code":200,"Message":"Place added successfully","Content":""});jQuery16203473509402899789_1315368234762 est votre demande de rappel (vous pouvez l'obtenir via querystring) {"Code":200,"Message":"Place added successfully"} est votre réponse JSON

Questions connexes