我需要将控制器的json响应传递给多个视图。有没有办法在cakephp中实现这个?
答案 0 :(得分:0)
你不需要CakePHP来做到这一点,你只需要JavaScript。有了JQuery的方法,但这是一个简单的JS方法:
var request = new XMLHttpRequest();
request.open('GET', '/controller/data.json', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Success!
var data = JSON.parse(request.responseText);
console.log(data);
// Now you can update your view here.
} else {
// We reached our target server, but it returned an error
console.log(error)
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
如果我误解并且您希望使用相同的控制器操作(不一定是JSON)使用不同的视图,则可以在视图的控制器操作中执行此操作:
$records = $this->Record->find('all');
$this->set('records', $records);
switch($variable){
case "value1":
$this->render("view1");
break;
case "value2":
$this->render("view2");
break;
case "value3":
$this->render("view3");
break;
}
其中view1为/View/Record/view1.ctp
,等等。