[英]CakePHP Jquery.ajax()
好吧,我是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);
},
})
});
})
總是出現錯誤的原因是,因為您永遠不會從必須執行json回顯的操作中返回響應,您只需設置數據即可。
您還應該在控制器方法中進行某種驗證,如果具有提供的ID的模板不存在,會發生什么情況? 您將得到一個錯誤,並且不進行處理。
不確定這個字符串
$this->layout = false;
像這樣創建新的空布局ajax.ctp
<?=$content_for_layout?>
並嘗試使用它
$this->layout = 'ajax';
和....您可以嘗試將這種方式用於ajax請求
$.get('/controller/action/'+Math.random(),{},function(data){
$('#result').html(data);
});
1. $this->autoRender = false;
或$this->viewBuilder->layout('ajax');
(對於Cakephp 3.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`
}
它會幫助你。
首先,您應該回顯結果,然后退出函數或將其設置為autoRender = false;。 要進行調試,您應該使用開發人員工具。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.