dtef9322 2013-02-24 04:05
浏览 82
已采纳

在类和函数中使用PHP读取/输出JSON

I normally get all JSON data using Jquery however I currently need to do it using only PHP.

Essentially this is how I normally get and output it with Jquery: (Snippet, not whole code)

$.post('getdata.php', {uid:uid} , function(data){
    if(data){   
    $.each(data, function(key, data) {
    $('#div #span-'+key).html(data);
    });

}

} , 'json')

Where uid is the value passed to php for use in querying the database.

And this is the php back end: (Again just a snippet of the JSON section)

while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
    $ret["ID"]       = $row['id'];
    $ret["username"] = $row['username'];
    $ret["email"]    = $row['email'];
    $ret["age"]      = $row['age'];
    echo json_encode($ret);
}

And obviously on the output page along with jquery I initiate the class and function:

$class = new retrieveData();
$class->userDetails();

Then to output the individual parts of the array where I want I would create a span with the same unique key for the particular array part as set out in jquery.

How would I go about converting the jquery part of this into PHP?

  • 写回答

2条回答 默认 最新

  • douguanyun2169 2013-02-24 04:52
    关注

    So if im understanding you you just want to rework the whole ajax side to sending off a request from the server:

    $ch = curl_init($theUrlThatReturnsTheData);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, array('uid' => $uid));
    curl_setopt($ch, CURLOPT_POST, true);
    $jsonData = curl_exec($ch);
    
    $data = json_decode($jsonData);
    

    Now do whatever it is you need to do with json... assuming from your jquery fragment thats something like this:

    <div id="<?php echo $uid ?>">
       <?php foreach($data as $key => $value): ?>
           <span id="span-<?php echo $key ?>">
             <?php echo $value ?>
           </span>
       <?php endforeach; ?>
    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求帮我调试一下freefem代码
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图