du1462 2014-06-16 18:02
浏览 14

如何使用json通过ajax发送php对象?

I have the following ajax code:

            $.ajax({
                type: 'post',
                url: '/conversation/test',
                data: { conversation: JSON.stringify(<?php echo json_encode($conversation) ?>) },
                success: function (response) {
                    console.log(response);
                }
            });

Now I have on my test.php:

<?php

    $conversation = json_decode($_POST['conversation']);


 ?>

<?php foreach ($conversation->getUsers() as $conUser) {
    // Skip current user
    if ($conUser->getId() == UserSession::getUserId()) {
       continue;
    } ?>
    <a href="/<?php echo $conUser->getUri(); ?>/"><?php echo $conUser->getName(); ?></a>
<?php } ?>

And my response on the console is:

<br />
<b>Fatal error</b>:  Call to undefined method stdClass::getUsers() in     <b>/Users/msalamanca/PhpStorm/pinporn/trunk/application/views/default/conversation/test.php</b> on line <b>8</b><br />

I don't understand what I am doing wrong here.

  • 写回答

1条回答 默认 最新

  • dongshan3806 2014-06-17 13:13
    关注

    Finally I understood what I was doing wrong. So on my view, I did the following:

        <div id="messages-widget">
    
        </div>
    
        <!--  Updates the conversation display and check for new messages  -->
        <script>
            $(document).ready(function () {
    
                $.post( "/conversation/messages", { conId: <?php echo $conversation->getId(); ?> })
                     .done(function (data) {
                          $('#messages-widget').html(data);
                });
    
    
            });
    
        </script>
    

    Then in my Controller I just did the following:

        public function messages($args=array()) {
    
            $conId = $args['conId'];
    
            // Get current conversation
            $conversation = ConversationModel::getConversationById($conId);
    
            DataHolder::getInstance()->addObject('conversation', $conversation);
        }
    

    So like this, my view will have the conversation object that I wanted, with its properties. Doing it like this, I can use the getters and setters that I needed.

    评论

报告相同问题?

悬赏问题

  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口