Loading...
Développement-code

JSON et JSONP avec PHP

Voici comment récupérer des données au format JSON en PHP avec JQUery.

JSON (JavaScript Object Notation) est un format de données textuel, générique, dérivé de la notation des objets du langage ECMAScript. Il permet de représenter de l’information structurée. Créé par Douglas Crockford, il est décrit par la RFC 4627 de l’IETF.
Un document JSON ne comprend que deux éléments structurels :

des ensembles de paires nom / valeur ;
des listes ordonnées de valeurs.

Ces mêmes éléments représentent 3 types de données :

des objets ;
des tableaux ;
des valeurs génériques de type tableau, objet, booléen, nombre, chaîne ou null.

Code côté PHP json.php

< ?php header('Cache-Control: no-cache, must-revalidate'); header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); header('Content-type: application/json'); $data[1]['id'] = "1"; $data[1]['value'] = "value1"; $data[2]['id'] = "2"; $data[2]['value'] = "value2"; echo json_encode($data); ?>

Page HTML appelant avec JQuery


$.ajax({
url: "json.php",
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: onLoadData
});
function onLoadData(data) {
alert("I load data");
};

JSONP pour JSON with padding (en français, « JSON avec formatage ») est une extension dans laquelle le nom de la fonction de retour est indiqué. L’idée originale proviendrait du blog MacPython en 2005 et est maintenant répandu dans les applications Web 2.0, telle que Google’s toolkit Applications. Des améliorations sont prévues pour y ajouter des arguments.

JSONP utilise des balises de scripts, les appels sont ouverts. Ainsi, JSONP peut être inapproprié pour transporter des informations confidentielles.

Code côté PHP jsonp.php

< ?php header('Cache-Control: no-cache, must-revalidate'); header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); header('Content-type: application/json'); $data[1]['id'] = "1"; $data[1]['value'] = "value1"; $data[2]['id'] = "2"; $data[2]['value'] = "value2"; echo $_GET['callback'] . '('.json_encode($data).')'; ?>


$.ajax({
url: "jsonp.php",
contentType: "application/json; charset=utf-8",
dataType: 'jsonp',
success: onLoadData
});
function onLoadData(data) {
alert("I load data");
};

12 comments
  1. aco

    Hum, et si on veut qu’il soit pris en compte par le cache du browser ?
    Je tente depuis 2 heures sans résultat (avec Chrome)

  2. kd12

    I truly wanted to compose a brief note to be able to thank you for these awesome recommendations you are sharing at this site. My time-consuming internet research has at the end been honored with reasonable details to exchange with my good friends. I would state that that most of us visitors are truly lucky to dwell in a perfect network with so many brilliant people with very beneficial techniques. I feel somewhat grateful to have encountered your site and look forward to plenty of more amazing moments reading here. Thank you once again for everything.

  3. curry 5

    I have to show my affection for your generosity giving support to people who really need assistance with the situation. Your special dedication to passing the solution along ended up being unbelievably helpful and has specifically empowered guys and women much like me to arrive at their dreams. Your entire insightful useful information indicates a great deal to me and even more to my office colleagues. Thank you; from each one of us.

  4. bape hoodie

    I and also my pals were found to be studying the excellent solutions found on your site then at once I got a horrible suspicion I never thanked the web blog owner for those techniques. These young men appeared to be as a result stimulated to read all of them and have now undoubtedly been making the most of those things. I appreciate you for truly being simply helpful and also for using this form of outstanding guides most people are really needing to discover. My honest apologies for not expressing gratitude to you earlier.

  5. lebron 16

    I must show my appreciation for your kindness for those who have the need for assistance with that subject. Your real commitment to getting the message throughout was remarkably beneficial and has in most cases allowed ladies much like me to reach their desired goals. Your amazing warm and friendly report implies a great deal a person like me and especially to my peers. Warm regards; from all of us.

  6. nike off white

    I would like to express my appreciation for your kindness for folks who actually need assistance with this one concept. Your real dedication to getting the solution up and down came to be extremely productive and have continually allowed men and women much like me to arrive at their aims. Your own valuable tutorial signifies much to me and somewhat more to my mates. Thanks a lot; from each one of us.

  7. golden goose

    I together with my guys ended up checking out the excellent tips and hints on your website and then all of a sudden got an awful feeling I never expressed respect to the web blog owner for those strategies. All the women happened to be absolutely thrilled to study them and already have in actuality been using them. Thanks for indeed being so thoughtful as well as for having these kinds of beneficial subject matter millions of individuals are really desperate to be informed on. My sincere apologies for not saying thanks to you sooner.

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *