简体   繁体   中英

How to read data from JSON object

I have a PHP script that selects some data from mysql and throw it into the following line:

$json_arr[] = array ('date'=>$human_date,'weight'=>$data['weight']);

As I run of a server with PHP4 I am using the Services_JSON ( http://pear.php.net/pepr/pepr-proposal-show.php?id=198 ) script to JSON-ify the data:

$json = new Services_JSON();
echo $json->encode($json_arr);

In the JS file I want to show all the weights & dates:

$.getJSON('ajax/getweights.php', {userid: userid}, function(data) { 

  $.each(data, function(k, v) {
    alert(v + ': ' v);
  });
});

How ever when I run the script, I dont get the wanted result, eg 2011-01-10:90,2011-01-15:92, 2011-01-18:89.

Im rather new to jQuery, and I have been searching the net for answers and I have tried to figure out how to read those data - I hope someone can help me :)

Assuming the server sends the data in the following format:

[ { date: '2011-01-10:90', weight: '1' }, 
  { date: '2011-01-15:92', weight: '2' }, 
  ...
]

you could:

$.each(data, function(k, v) {
    alert('date: ' + v.date + ' | weight: ' + v.weight);
});

Easier way to achieve this:

$json_arr[] = array(
  'date' => $human_date,
  'weight' => $data['weight']
);

$json = new Services_JSON();
echo 'processData(' . $json->encode($json_arr) . ')';

And JavaScript:

// Callback function which processes the data
function processData(data) {
  for(var i = 0; i < data.length; i++)
    alert(data[i].date + ', ' + data[i].weight);
}

// Here we import the data
var s = document.createElement('script');
s.src = 'ajax/getweights.php';
document.body.appendChild(s);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM