Skip to content Skip to sidebar Skip to footer

Ajax Get From A Json Tree

I'm just starting out with AJAX, trying to use JQuery's $.getJSON function (or any related, ie $.load(), $.ajax(), etc). I have a JSON file with a structure something like this: [

Solution 1:

Short answer - you can't do this directly with AJAX. jQuery can extract portions of HTML and XML documents, but not JSON.

Easiest answer - retrieve the entire object (you have to, anyway) and use jsonpath to get the structure you want

Longer answer - retrieve the entire object, and traverse it yourself to get the object you want

Best answer - make the email address a parameter to whatever script produces the json and have the server only return the data you want.

Solution 2:

Once the JSON is parsed, you pass it to a callback function - then you can manipulate that array however you need.

You'll probably want some custom code:

$.getJSON(myURL, function(data) {
    /* data is an array of objects */for (var i=0, j=data.length; i<j; i++) {
        if (data[i].email === some_value) {
            /* do something with data[i] */
        };
    };
});

http://api.jquery.com/jQuery.getJSON/

Solution 3:

You can 1 of 2 things, loop through the array on the client side, or dynamically have users.json generated on each call (this assumes a backend server language like php)

Using dynamically generated json file

JS

$.ajax({
   url:"/users.json.php",
   data:{
      useremail:"someusersemail@here.com"
   }
   type:"POST",
   dataType:"json",
   success:function(userdata){
      //users data will be in userdataconsole.log(userdata.email);
   }
})

Server Script (assumes PHP): users.json.php

$email = $_POST['useremail'];

//get user data based on email
...

echo json_encode($userdata);
die;

generated json file should end up outputing something like

{"id": 1,"email": "user@domain.com","password": "password"}

Loop Method: loop through the users array on client side

$.ajax({
   url:"/users.json",
   dataType:"json",
   success:function(data){
      for(i=0;i<data.length;i++) {
         var user = data[i];
         if(user.email == "someemail@gmail.com") {
            //do what you need to with user data
         }
      }
   }
})

Post a Comment for "Ajax Get From A Json Tree"