简体   繁体   English

如何从JSON对象读取数据

[英]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: 我有一个PHP脚本,该脚本从mysql中选择一些数据并将其放入以下行:

$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: 当我使用PHP4运行服务器时,我正在使用Services_JSON( http://pear.php.net/pepr/pepr-proposal-show.php?id=198 )脚本对数据进行JSON修饰:

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

In the JS file I want to show all the weights & dates: 在JS文件中,我想显示所有的重量和日期:

$.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. 但是,当我运行脚本时,却没有得到想要的结果,例如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 :) 我对jQuery相当陌生,我一直在网上寻找答案,并且试图弄清楚如何读取这些数据-我希望有人可以帮助我:)

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: 和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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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