嗯,我是CakePHP的新手。所以这是一个痛苦的一天。这是我的代码:
templates_controller.php
function reajax($id = NULL) {
$this->layout = false;
$this->Template->id = $id;
$template = $this->Template->read();
$this->set('result', $template['Template']['content']);
}reajax.ctp
echo $result;js文件
$(document).ready(function() {
$(".abcd").click(function(event){
event.preventDefault();
var id = this.id;
$.ajax({
type:"GET",
url:"/templates/reajax/" + id,
success : function(data) {
alert('success');
$("textarea").text(data);
},
error : function() {
alert(id);
},
})
});
})单击文件
<ul class="content-box-tabs">
<?php echo $html->link($html->image('thumbnails/'.$template['Template']['thumbnail'], array('alt' => 'test', 'height' => '120', 'width' => '110')), array('controller' => 'templates', 'action' => 'reajax'), array('class' => 'abcd', 'id' => $template['Template']['id'], 'escape' => false))?>
</ul>每次我得到错误结果时,我都不知道我的代码有什么问题。有谁可以帮我?提前谢谢。
当我编辑下面的JS文件时,一切都进行得很顺利。我不知道这是否是CakePHP的错误,或者我的代码是否有其他错误。我需要一个蜘蛛侠!
$(document).ready(function() {
$(".abcd").click(function(event){
event.preventDefault();
var id = this.id;
$.ajax({
type:"GET",
url:"/cakephp/templates/reajax/" + id,
//url: "/templates/reajax/" + id,
success : function(data) {
alert('success');
$("textarea").text(data);
},
error : function() {
alert(id);
},
})
});
})发布于 2011-09-02 01:49:01
获得错误的原因总是因为您从未从必须执行json的操作返回响应--例如,您只是在设置数据,仅此而已。
您还应该在控制器方法中进行某种验证,如果提供的ID模板不存在,会发生什么情况?您将得到一个错误,而不是处理它。
发布于 2011-09-01 11:32:24
不确定这串
$this->layout = false;创建新的空布局ajax.ctp如下
<?=$content_for_layout?>试着用它
$this->layout = 'ajax';还有..。您可以尝试使用这种方式处理ajax请求。
$.get('/controller/action/'+Math.random(),{},function(data){
$('#result').html(data);
});发布于 2016-08-12 17:13:06
1.$this->autoRender = false;或$this->viewBuilder->layout('ajax');(用于Cakephp3.0&在布局文件夹中创建一个ajax.ctp ) ajax.ctp应该如下所示
<?php
echo $this->fetch('content') ;
?>您不需要为ajax函数创建.cpt,因为ajaxFunction可以返回一些值,而不是html。
然后,您可以检查它是否是ajax请求。(这对于最佳实践来说并不重要)
if ($this->request->is('ajax')) {
// do your logic here
}现在您的代码应该如下所示
function reajax($id = NULL) {
$this->autoRender= false;
$result = "Some value";
echo $result;`enter code here`
}会对你有帮助的。
https://stackoverflow.com/questions/7267821
复制相似问题