dtwupu6414 2010-08-01 14:44
浏览 38
已采纳

AJAX调用和JSON数据

Good day!

I'm learning to create AJAX calls to PHP scripts.

Basically, I want to find the best solution to handle AJAX calls. In this question you can find my client-side part of the code.

Basically, I'd like to verify my knowledge here and if I'm wrong, get any tips how to make it correct way.

So... I'm using KohanaPHP framework (but also going to learn ZendFramework). I created a test controller with following code:

public function __construct() 
{
    if (request::is_ajax()) {
        $this->auto_render = FALSE;
        header('content-type: application/json');
    }
}

public function index()
{
    $result['success'] = 1;

    $test_model = new Test_Model;
    $items = $test_model->get_test_rows();
    foreach($items as $item):
        $rows[] = $item;
    endforeach;     
    $result['rows'] = json_encode($rows);

    if (request::is_ajax()) {
        echo json_encode($result);
    }
}

Now I got few questions related to this code. Let me ask them.

1) In thread mentioned above I was told I do not have to use $.parseJSON(); function and I can use data.rows[0]name instead. Unfortunately, it does not work. For the is't not a big problem, I can use $.parseJSON(); but I'd like to know if there's any bug in my PHP code?

2) I'm trying to learn good practices and techniques and I'm try to not violate MVC rules. I have a MVC related question. Is it possible to use echo() in controllers? You may notice I'm using it to return JSON encoded data.

  • 写回答

3条回答 默认 最新

  • douzi5214 2010-08-01 16:21
    关注

    To answer question (2): Yes, it is normally bad form to echo in the controller. I'd even go as far to say it's bad form to build any sort of string the controller either.

    However, in the case where all that's being output is json, I think it's simply easier, and more concise to just echo json_encode($results); If you really want to be an MVC purist, you can always create a file that does nothing but echo json(...);.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等