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

33 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.

  8. russell westbrook shoes

    I have to voice my love for your kindness in support of persons who absolutely need help on this one matter. Your personal dedication to passing the solution all over appeared to be especially insightful and have specifically made women like me to attain their desired goals. Your amazing warm and friendly tutorial means a lot to me and a whole lot more to my office workers. Best wishes; from all of us.

  9. supreme clothing

    Thank you a lot for giving everyone a very splendid opportunity to read critical reviews from here. It really is so pleasant and jam-packed with a good time for me personally and my office mates to search your website minimum 3 times a week to read through the latest secrets you have got. And of course, I am also usually motivated with your powerful inspiring ideas you serve. Selected 1 ideas on this page are surely the most efficient we have had.

  10. whect

    When it comes to office cleaning, Cleaning World Inc. does it better than anyone else! Our professional corporate cleaning services will get your office in shape in no time! Shine Facility Services is a privately owned and operated business that provides office cleaning and building maintenance services to businesses in San Francisco. The company specializes in providing janitorial services that include carpet cleaning, trash removal and recycling, bathroom disinfecting, tile floor cleaning, and concrete floor machine cleaning. It also uses modern cleaning equipment and environmentally friendly cleaning products certified by third-party eco-labels, including an EPA N-listed disinfectant. Shine Facility Services has more than 15 years of experience in the office cleaning industry. https://juliet-wiki.win/index.php/Best_way_to_clean_carpet Get your free quote today and receive the best quality services performed by one of Houston’s best carpet cleaning companies around. Carpet Cleaning 3 Areas For $139 Anna was absolutely fantastic!! She removed multiple pet stains in less than an hour and was a hoot and a half! Hardworking and it shows. I will definitely call her next time I need my carpets cleaned!! 10/10 Once you’ve rid your carpet of cat urine odors, you’ll want to ensure that they don’t return. Be sure that all odors are completely neutralized and undetectable. If your cat can still smell them, it may entice him to urinate in the same area again. Most importantly, find out why your cat is peeing outside of his litter box . Have your vet check for health problems and urinary infections, and invest some time in a little detective work so that you don’t have to face that horrible smell again. 

  11. yeezy 500

    I wanted to put you that little bit of note to finally thank you very much once again for your personal nice opinions you have featured at this time. This is wonderfully generous of you to present unhampered precisely what a number of us would have offered for sale for an e-book to help make some dough for their own end, most notably considering the fact that you might have done it in case you desired. Those basics as well served as a good way to be certain that other individuals have a similar dreams like mine to know the truth lots more in terms of this problem. I know there are several more enjoyable instances up front for folks who look into your site.

  12. kd13

    My wife and i have been ecstatic when Raymond could deal with his analysis because of the ideas he was given while using the blog. It’s not at all simplistic to just be giving out instructions that the rest may have been selling. Therefore we acknowledge we now have you to be grateful to because of that. The entire illustrations you have made, the straightforward site navigation, the friendships your site make it easier to engender – it is mostly terrific, and it’s leading our son and our family imagine that that subject is cool, and that’s unbelievably pressing. Many thanks for the whole lot!

  13. lebron 18

    I must convey my gratitude for your kindness giving support to people that have the need for guidance on your theme. Your real commitment to getting the solution all over became astonishingly powerful and have really encouraged people just like me to attain their pursuits. Your new useful guide indicates much a person like me and still more to my colleagues. Thanks a ton; from each one of us.

  14. lebron 18

    I want to point out my gratitude for your kind-heartedness supporting women who must have guidance on your idea. Your very own commitment to passing the solution up and down appears to be amazingly invaluable and has in most cases empowered folks like me to arrive at their pursuits. Your personal warm and friendly suggestions can mean a great deal a person like me and somewhat more to my office colleagues. Best wishes; from everyone of us.

Laisser un commentaire

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