2014-10-10 33 views
2

我使用$就在CakePhp2.4.5-我第一次讀了很多關於計算器帖子和W3Schools的和jQuery網站還做了其他的研究,但不能到控制器瞭解我應該如何解決我的問題。 我想將數據從我的第一視圖發送到控制器index.ctp

$.ajax({ 
       type: 'POST', 
       url: 'meers/client', 
       datatype:'json', 
       cache: false, 
       data: {myVal:'Success!'}, 
       success: function(){alert('AjaX Success')}, 
       error: function(){alert('AjaX Failed')} 
      }) 
       .done(function(){ 
        alert('AjaX Done!'); 
       }); 

警報顯示「阿賈克斯成功」。

在我的控制器

我有

public function client(){ if($this->request->isAjax()){ $this->set('ajaxTest','Success'); }}

在我的第二個觀點client.ctp我有。

if(isset($ajaxTest)){ echo $ajaxTest; }else{ echo 'ajaxTest not Set.'; }

問題。我總是在我的Client.ctp視圖「ajaxTest not Set」中獲取msg。 我在做什麼錯?或如何做到這一點?由於

+0

你如何得到這個「ajaxTest沒有設置」?通過螢火蟲或使用直接的網址? – 2014-10-10 19:32:38

+0

你可以在我的View client.ctp中看到如果$ ajaxTest被設置或者沒有,我有一個if語句。 – Meer 2014-10-10 19:36:02

+0

我不是CakePHP開發者,但不應該使用'is('ajax')'而不是'isAjax'?看起來[第二語法](http://book.cakephp.org/2.0/en/controllers/request-response.html#inspecting-the-request)已被棄用。請注意JavaScript是區分大小寫的,'datatype'屬性應該是'dataType'。 – undefined 2014-10-10 23:35:38

回答

2

我認爲你的問題是在url因爲「米爾斯/客戶端」在沒有一個路線

$.ajax({ 
     type: 'POST', 
     url: "<?php echo $this->Html->url(array('controller' => 'YourController','action' => 'YourAction')); ?>", 
     datatype:'json', 
     cache: false, 
     data: {myVal:'Success!'}, 
     success: function(){alert('AjaX Success')}, 
     error: function(){alert('AjaX Failed')} 
    }) 
     .done(function(){ 
      alert('AjaX Done!'); 
     }); 

或可以探測給人一種路由器:

$.ajax({ 
     type: 'POST', 
     url: "<?php echo Router::url(array('controller' => 'YourController', 'action' => 'YourAction'), true); ?>", 
     datatype:'json', 
     cache: false, 
     data: {myVal:'Success!'}, 
     success: function(){alert('AjaX Success')}, 
     error: function(){alert('AjaX Failed')} 
    }) 
     .done(function(){ 
      alert('AjaX Done!'); 
     }); 

,你可以看到其他的例子:

http://www.dereuromark.de/2014/01/09/ajax-and-cakephp/

Making jquery ajax call from view to controller in cakephp 2.x

+0

@#Widrogo感謝您的回覆,但如果我給這個功能的假路線,我通過給試過它應該給一個錯誤一個錯誤的網址。但在我的代碼中,AjaX返回成功。那它呢? – Meer 2014-10-10 23:21:08

+0

我用你的URL版本,但它給了我控制檯中的這個錯誤 未捕獲的SyntaxError:意外的令牌ILLEGAL 和我發現的是Html Helper現在包括我的根應用名稱在Url/MyAppName/meers/client中,我認爲它不可訪問。 – Meer 2014-10-10 23:25:23

+0

在你的控制器中進行調試debug($ this-> request-> isAjax());和做一個請求取決於蛋糕的版本。 1.3.x: $ this-> ResquestHandler-> isAjax(); 2.x $ this-> request-> is('ajax'); – CoolLife 2014-10-10 23:47:58