CakePHP - ajax 请求的布局文件夹
CakePHP - Layout folder for ajax-requests
我的申请将有两种不同的请求类型,AJAX 和 JSON。
AJAX 应输出 html-代码; JSON应return纯JSON代码。
我设法通过调用这样的控制器操作来发送 JSON 输出:/index.json --> Outputs json code,视图位于 /View/Test/json/index.ctp
下
如何在 /View/Test/ajax/index.ctp 中为 /index.ajax[=29 这样的请求存储视图文件=]
我试过设置
Router::parseExtensions('json', 'ajax');
在我的 /Config/routes.php 但随后调用 index.ajax 只是输出了 /View/Test/ajax/index.ctp
的标准 /View/Test/index.ctp insetad
我做错了什么?
谨致问候,
Battlestr1k3
Ajax是方法,不是数据类型。
您可能正在发出一个 ajax 请求,该请求将 return json 在这种情况下您可以在 json 视图中使用它或解码它并在标准视图。
如果您通过 ajax 请求重新调整 json 对象或数组以显示为 HTML,您也可以使用 jquery 解析它。请参阅此处了解更多信息:
http://api.jquery.com/jquery.parsejson/
编辑以下评论:
首先,你需要有一个视图文件来输出HTML,这将在:
app/View/Tests/index.ctp
app/View/Tests/add.ctp
等等
然后你的控制器中就有了相应的方法:
public function index(){
//index method here
}
此时,当您在浏览器中转到 /tests/index.html 时,您的索引视图将呈现,并且您在 [=43= 中设置的所有 HTML 结构] 文件将显示。但是,您将没有数据,因为您尚未从数据库中检索数据或将其设置为供视图使用。
因此,要渲染它,您 运行 您的 ajax 调用并将 url 设置为 /Tests/index
然后将逻辑添加到控制器中的索引函数,例如:
if($this->RequestHandler->isAjax()){
//debug can cause problems with AJAX requests so switch it off if it is on
Configure::write('debug', 0);
//you need to pass the id through in the data parameter of your ajax call
$id = $this->request->query['id'];
$settings = array(
'conditions' => array('Test.id' => $id),
);
$data = $this->Test->find('first', $settings);
return json_encode($data);
}
这将 return 一个 json 数组,你可以用 jquery 解析它并附加到你的 HTML.
我的申请将有两种不同的请求类型,AJAX 和 JSON。 AJAX 应输出 html-代码; JSON应return纯JSON代码。 我设法通过调用这样的控制器操作来发送 JSON 输出:/index.json --> Outputs json code,视图位于 /View/Test/json/index.ctp
下如何在 /View/Test/ajax/index.ctp 中为 /index.ajax[=29 这样的请求存储视图文件=]
我试过设置 Router::parseExtensions('json', 'ajax'); 在我的 /Config/routes.php 但随后调用 index.ajax 只是输出了 /View/Test/ajax/index.ctp
的标准 /View/Test/index.ctp insetad我做错了什么?
谨致问候,
Battlestr1k3
Ajax是方法,不是数据类型。
您可能正在发出一个 ajax 请求,该请求将 return json 在这种情况下您可以在 json 视图中使用它或解码它并在标准视图。
如果您通过 ajax 请求重新调整 json 对象或数组以显示为 HTML,您也可以使用 jquery 解析它。请参阅此处了解更多信息:
http://api.jquery.com/jquery.parsejson/
编辑以下评论:
首先,你需要有一个视图文件来输出HTML,这将在:
app/View/Tests/index.ctp app/View/Tests/add.ctp
等等
然后你的控制器中就有了相应的方法:
public function index(){
//index method here
}
此时,当您在浏览器中转到 /tests/index.html 时,您的索引视图将呈现,并且您在 [=43= 中设置的所有 HTML 结构] 文件将显示。但是,您将没有数据,因为您尚未从数据库中检索数据或将其设置为供视图使用。
因此,要渲染它,您 运行 您的 ajax 调用并将 url 设置为 /Tests/index
然后将逻辑添加到控制器中的索引函数,例如:
if($this->RequestHandler->isAjax()){
//debug can cause problems with AJAX requests so switch it off if it is on
Configure::write('debug', 0);
//you need to pass the id through in the data parameter of your ajax call
$id = $this->request->query['id'];
$settings = array(
'conditions' => array('Test.id' => $id),
);
$data = $this->Test->find('first', $settings);
return json_encode($data);
}
这将 return 一个 json 数组,你可以用 jquery 解析它并附加到你的 HTML.