在蛋糕PHP 3.0 jQuery的Ajax调用蛋糕、PHP、jQuery、Ajax

2023-09-10 18:27:02 作者:别熬夜.

你好, 我试图做一个Ajax请求的观点a从控制器B:

Hi, I'm trying to make a ajax request to the view A from the controller B like this :

在视图中的:

var tab = new Array();
    function updateResult(){
            $.ajax({
                type:"POST",
                url:"<?php echo Router::url(array('controller'=>'B','action'=>'viewresult'));?>",
                dataType: 'text',
                async:false,
                success: function(tab){
                    alert('success');
                },
                error: function (tab) {
                    alert('error');
                }
            });
    }

在控制器B:

public function viewresult()
{
echo 'SUCCESS';
}

现在的问题是,在阿贾克斯的'反应',我已经成功,但也是整个视图中的,我不明白为什么? 我想只有成功...

The problem is that in the 'response' of ajax, I've 'SUCCESS' but also the entire view A, I don't understand why... I want only 'SUCCESS'...

在此先感谢!

推荐答案

要实现这一目标是加入死亡()在你的函数的末尾,因此$最简单的方法p $ pvents加载整个布局:

The easiest way to achieve it is adding die() at the end of your function so it prevents to load whole layout:

public function viewresult()
{
    echo 'SUCCESS';
    die;
}

public function viewresult()
{
    die('SUCCESS');
}

但更传统的方法是使用 JSONView 。你的行动应如下所示:

But more conventional way is using JSONView. Your action should look as follows:

public function viewresult()
{
    $this->set('text', 'SUCCESS');
    $this->set('_serialize', ['text']);
}

您还需要加载 RequestHandler的组件在控制器初始化()方法:

You also have to load RequestHandler component in initialize() method in your controller:

public function initialize()
{
    parent::initialize();

    $this->loadComponent('RequestHandler');
}

您需要为以后在 routes.php文件连接的所有路由设置允许扩展名:

You need to set allowed extensions for all routes connected later in routes.php:

Router::extensions('json', 'xml');

现在,您可以访问你的行动将扩展 .json 在结束了它的网址,所以你需要修改调用Ajax网址:

Now you can access your action adding extension .json at the end of it's URL, so you need to modify ajax call url:

url:"<?php echo Router::url(array('controller'=>'Main','action'=>'viewresult', '_ext' => 'json'));?>"

这一切,但请记住,这个解决方案迫使你处理JSON数组中的响应。在这个例子中输出将看起来如下:

That's all, but keep in mind that this solution force you to handle JSON array in response. In this example output will be looks as follows:

{"text": "SUCCESS"}