Json et ajax

smendili - 25 nov. 2012 à 12:00
 smendili - 25 nov. 2012 à 15:23
Bonjour,

j'ai le code suivant .html :
<html>
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">

<script type="application/javascript">
function loadJSON()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{

// Parse the JSON data structure contained in xmlhttp.responseText using the JSON.parse function.
var JSONObject = JSON.parse(xmlhttp.responseText);

// The JSONObject variable now contains the data structure and can be accessed as JSONObject.firstName and
// JSONObject.lastName. Assign the object members to the DOM elements FirstName and LastName so that they get
// displayed on the page
document.getElementById("FirstName").innerHTML = JSONObject.firstName;
document.getElementById("LastName").innerHTML = JSONObject.lastName;
}
}
xmlhttp.open("GET","JSON.txt",true);
xmlhttp.send();
}
</script>

<title>JSON and AJAX</title>
</head>


Prince


Vivian

Update Name
Click this button to update the page


</html>

et le format json "JSON.txt" suivant:
{"firstName": "Isabelle", "lastName": "Solomon"}


j'ai essayer de l'implémenter mais ça ne marche pas, je ne sais pas si vous pouvez m'aidez la dessus.

Merci

2 réponses

f0xi Messages postés 4205 Date d'inscription samedi 16 octobre 2004 Statut Modérateur Dernière intervention 12 mars 2022 35
25 nov. 2012 à 15:00
Impossible de faire fonctionner ton code, correction, test, correction ... rien de rien.

J'ai donc voulus tester avec JQuery, ça marche bien.

le fichier (names.json)
{
  "firstName": "Isabelle", 
  "lastName": "Solomon"
}


et le fichier HTML (index-json.html)
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type">

<title>JSON and AJAX</title>

<script type="text/javascript" name="jquery" src="http://code.jquery.com/jquery-1.8.3.min.js">
</script>

<script type="text/javascript">
function getjsondata(){
  $.getJSON('names.json', function(data){
    $('#firstName').html(data.firstName);
    $('#lastName').html(data.lastName);
  });
}
</script>
</head>

  
Prince

  
Vivian

  
  
  
  Click this button to update the page


</html>


Je n'ai pas reussi à comprendre pourquoi ton code ne fonctionne pas.

________________________________________________________
besoin de câbles audio, vidèo, informatique pas cher ?
0
J'ai essayé avec tes modifications mais ça ne marche pas toujours
Il n'y a pas de m.à.j quand je clique sur le bouton "Update Name".
0
Rejoignez-nous