加载 Cakephp 的视图并将它们发送到我的 Phonegap 项目

Loading the views of Cakephp and send them to my Phonegap Project

我正在开发一个在服务器端使用 Cakephp 2.6.0 并在客户端使用 PhoneGap 5.4.1 的应用程序,使用 JSON 作为访问服务器端的中间层。

请问是否可以加载views的内容,使用JSON发送到客户端,使用JavaScript显示?如果是,我该怎么做? 任何帮助将不胜感激。

我认为最好的方法是将 Cordova/PhoneGap 应用程序用作客户端(视图),将 CakePHP 用作服务器端(模型和控制器)。从您的 PhoneGap 应用程序,您可以通过 ajax 与您的 CakePHP 应用程序进行通信,以共享数据或执行一些 CRUD 操作。

我试着给你一些灵感,并向你展示如何通过将 userId 从你的 cordova 应用程序传递到 cakephp 来获取用户数据:

IMPORTANT: I have skiped the authentification part in this example. For more information see CookBook 2.x - Authentification

Cordova/Phonegap:

document.addEventListener('deviceready', onDeviceReady, false);

function onDeviceReady() {    

   $.ajax({
      url : 'www.yourUrl.com/YourAppName/users/view/1', // 1 => userId
      data : {},
      dataType : 'json',
      success : function(result) {
         // do something with the result
         // e.g. access user name: result['User']['name'];
      },
      error : function(xhr, status, err) {
         // do something on error
      }
   });
}

CakePHP:

class UsersController extends AppController {

    public $name = 'Users';

    public function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allow('view');
    }

    public function view($userId = null){
        $this->autoRender = false;

        // use $this->Auth->User('id') insted of $userId 
        // as soon as you have implimented the user authentification
        $user = $this->User->findById($userId);
        echo json_encode($user); 
        die;
    }
}

编辑:

如果您想获得 json 的视图内容,请查看 derEuroMark 博客中的示例。他创建了一个 AjaxView,负责将内容映射到 JSON 结构,并自动尝试通过 "ajax" 子文件夹(View/ControllerName/ajax/favorites.ctp). Link: AjaxView