jquery - CakePHP 和 jQuery - 不显眼的操作

标签 jquery ajax cakephp unobtrusive

我正在尝试在 CakePHP 中执行一个不引人注目的操作来删除书签。 尽管它工作得很好,但我怀疑一定有更好的方法来做到这一点。有人可以指出我正确的方向吗?

function delete($id = null) {
  $ok = $this->Bookmark->delete($id);

  if($this->RequestHandler->isAjax()) {
    $this->autoRender = false;
    $this->autoLayout = false;
    $response = array('status' => 0, 'message' => 'Could not delete bookmark');

    if($ok) {
        $response = array('status' => 1, 'message' => 'Bookmark deleted');
    }

    $this->header('Content-Type: application/json');
    echo json_encode($response);
    exit();
  }
  // Request isn't AJAX, redirect.
  $this->redirect(array('action' => 'index'));
}

最佳答案

如果您计划更广泛地使用 AJAX 操作调用,那么走“过度杀伤”路线可能比走“不优雅”路线更值得。以下方法将您的应用程序配置为非常优雅地处理 AJAX 请求。

在routes.php中,添加:

Router::parseExtensions('json');

app/views/layouts/中创建一个新目录json,并在新目录中创建一个新布局default.ctp:

<?php
    header("Pragma: no-cache");
    header("Cache-Control: no-store, no-cache, max-age=0, must-revalidate");
    header('Content-Type: text/x-json');
    header("X-JSON: ".$content_for_layout);

    echo $content_for_layout;
?>

app/views/bookmarks/中创建一个新目录json,并在新目录中创建一个新 View delete.ctp:

<?php
    $response = $ok
        ? array( 'status'=>1, 'message'=>__('Bookmark deleted',true))
        : array( 'status'=>0, 'message'=>__('Could not delete bookmark',true));

    echo $javascript->object($response); // Converts an array into a JSON object.
?>

Controller :

class BookmarksController extends AppController()
{
    var $components = array('RequestHandler');

    function beforeFilter()
    {
        parent::beforeFilter();
        $this->RequestHandler->setContent('json', 'text/x-json');
    }
    function delete( $id )
    {
        $ok = $this->Bookmark->del($id);
        $this->set( compact($ok));

        if (! $this->RequestHandler->isAjax())
            $this->redirect(array('action'=>'index'),303,true);
    }
}

在调用 AJAX 的页面上,您可以将 AJAX 请求从 /bookmarks/delete/1234 更改为 /bookmarks/delete/1234.json .

这还为您提供了使用 app/views/bookmarks/delete.ctp View 处理对 /bookmarks/delete/1234 的非 AJAX 调用的选项.

您想要通过 AJAX 和 JSON 处理的任何进一步操作,都需要在 app/views/bookmarks/json/ 目录中添加 View 。

关于jquery - CakePHP 和 jQuery - 不显眼的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2510961/

相关文章:

php - Cakephp 如何从 GET 提交中检索数据

php - CakePHP 无法写入某些文件

javascript - 如何检查复选框是否被选中?

php - 将 mysql echo 作为 ajax 中的错误返回

javascript - AJAX 与 Rails 3 和 jQuery?

jquery - jQuery ajax 调用后 IE 7 重定向

javascript - 隐藏没有 val 的 div (ASP.NET MVC)

php - 如何使用 CakePHP3 ORM 获取字符串格式的 where 子句?

jquery - 使用带有正斜杠的pushState

jquery - 具有多个导航选项的 slider 丢失索引并且损坏或不合适?