普通网友 2016-10-23 17:19
浏览 73
已采纳

将CI_Model转换为JSON,然后将Send转换为AJAX

How to convert an object to JSON using json_encode and then send this JSON to AJAX as response?

CI_Model :

<?php

class TResponse extends CI_Model
{
    private $status;
    private $topics;

    public function __construct()
    {
        parent::__construct();
    }
}

Inside Controller :

$response = new Model\TResponse ();
$response->status = true;
echo json_encode($response);

AJAX :

$('#myform').on('submit', function (e)
        {
            e.preventDefault(); // prevent page reload
            $.ajax ({
                type : 'POST', // hide URL
                url : 'My_Controller/exec', // form validation file
                data : $('#myform').serialize (),
                dataType: 'json',
                success : function (data)
                {
                    console.log("ok");
                }
                , error: function(xhr, status, error)
                {
                    console.log(status+" "+error+" "+xhr)
                }
            });

PROBLEM :

When i execute that code result error. the error is "error Internal Server Error [Object object]". How to solve my problem?

  • 写回答

2条回答 默认 最新

  • dongxi2163 2016-10-23 19:52
    关注

    I don't understand why you're using $response = new Model\TResponse();. It not "the codeigniter way" to load a model. But I think it must be related to the problem because the code belows works perfectly for me.

    Notice I have made both class properties public. Private properties are not exposed and so would not be "presented" to json_encode().

    class TResponse extends CI_Model
    {
        public $status = FALSE;
        public $topics = ['php', 'stackoverflow', 'json'];
    
        public function __construct()
        {
            parent::__construct();
        }
    
    }
    

    In the controller

    $this->load->model('TResponse');
    $this->TResponse->status = TRUE;
    echo json_encode($this->TResponse);
    

    Your javascript is fine as is.

    If I use this

    success: function (data) {
        console.log(data);
    }
    

    This is what the console reports

    Object
      status: true
      topics: Array[3]
        0: "php"
        1: "stackoverflow"
        2: "json"
        length: 3
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置