2015-11-27 30 views
0

我試圖執行ajax請求時,鏈接是通過點擊傳遞id值。如果成功,嘗試提醒數據。請告訴我什麼是錯的。我想顯示view.ctp的數據,那麼AJAX請求後在index.ctp加載在CakePHP 2.7 ajax請求,但未能返回數據

$('a.view-btn').on('click', function(e){ 
     var view = $(this); 
     var id = view.data('id'); 
     var href = view.attr('href'); 

     $.ajax({ 
      url: href, 
      type: 'POST', 
      data: {product_id: id}, 
      success: function(data) { 
       alert(data); 
       $('div#view-contact').load(href + ' .view-contact'); 
      } 
     }); 
     console.log(id); 
    }); 

這是我的控制器編輯方法

public function view($id) {   
     if ($this->request->is('ajax')) { 
      $this->autoRender = false; 
      $this->set('contact', $this->request->data('product_id')); 
      echo "AJAX SUCCESS"; 
     } else { 
      $this->set('contact', $this->Contact->findById($id)); 
     } 
    } 
+0

鉻和mozilla我可以提醒「AJAX成功」,但它會重定向到/ contacts/view頁面。 –

回答

0

我試圖添加dataType: 'json'ajax

$('a.view-btn').on('click', function(e){ 
      var view = $(this); 
      var id = view.data('id'); 
      var href = view.attr('href'); 

     $.ajax({ 
      url: href, 
      type: 'POST', 
      dataType: 'json', 
      data: {product_id: id}, 
      success: function(data) { 
       $('div#view-contact').load(href + ' .view-contact'); 
      } 
     }); 
     e.preventDefault(); 
    }); 

在我看來,我的方法方法echo json_encode($contact)。它的工作原理。

public function view($id) {   
     if ($this->request->is('POST')) { 
      $this->autoRender = false; 
      $contact = $this->request->data('product_id'); 
      $this->set('contact', $contact); 
      echo json_encode($contact); 
     } else { 
      $this->set('contact', $this->Contact->findById($id)); 
     } 
    } 

但是有部分代碼我不明白。當我嘗試echo "ajax success";這意味着我的ajax請求成功?那麼爲什麼我不能加載我的視圖的內容,當我嘗試使用jquery $().load(href + ' .view-contact')加載它?

0
use e.preventDefault().It will stop your page to refresh 
$('a.view-btn').on('click', function(e){ 
     e.preventDefault(); 
     var view = $(this); 
     var id = view.data('id'); 
     var href = view.attr('href'); 

     $.ajax({ 
      url: href, 
      type: 'POST', 
      data: {product_id: id}, 
      success: function(data) { 
       alert(data); 
       $('div#view-contact').load(href + ' .view-contact'); 
      } 
     }); 
     console.log(id); 
    }); 
+0

是的,我嘗試過,但我怎麼能顯示view.ctp中的數據並顯示它的索引?我試圖$('div#view-contact')。load(href +'.view-contact');顯示它但失敗。 –

+0

什麼是href值? –

+0

/bootstrap_exercise/contacts/view/47先生。我試圖echo $ this-> request-> data('product_id'),但它返回空sir –