2013-05-25 33 views
0

#Edit我使用CakePHP 2.3.5CakePHP的 - 阿賈克斯工作不正常

我想知道什麼是我的Ajax請求,並控制行爲的問題。 這是我遇到的問題:

  1. 阿賈克斯 - POST請求總是失敗(我總是得到錯誤響應)
  2. 即使這樣,我可以O_O
  3. 到DATABSE添加新的用戶,即使我有beforeFilter到認識Ajax請求重定向仍然查看 (你可以在源見下面我已經添加autoRender放慢參數錯誤)

我真的不知道是怎麼回事了,我將是任何形式的幫助感激!

這裏的源代碼:

我的Ajax請求

$('.addUser').on('click', function(){ 
    var data = $('#UserAddForm').serialize();  
    $.ajax({ 
     dataType: "html", 
     type: "POST", 
     evalScripts: true, 
     url: 'Users/add', 
     data: data, 
     success: function(){ 
      $('#regInfo').html("User was created"); 
      $('#regInfo').css('color', 'darkgreen'); 

     }, 
     error: function(){ 
      $('#regInfo').html("User was not created"); 
      $('#regInfo').css('color', 'darkgreen'); 
     } 
    }); 
}) 

我UserController的CakePHP中

public function add() { 

if ($this->request->is('post')) { 
    $this->User->create(); 
    if ($this->User->save($this->request->data)) { 
     $this->Session->setFlash(__('The user has been saved')); 
    } else { 
     $this->Session->setFlash(__('The user could not be saved. Please, try again.')); 
    } 
}   

}

在我AppController的

public function beforeFilter(){ 
    if ($this->request->is('ajax')) { 
     Configure::write('debug', 0); 
     $this->autoRender = false; 
     $this->layout = 'ajax'; 
    } 
} 
+0

你有沒有試過在你的控制器中對ajax進行髒測試?我通常做的就是'if($ this-> data ['mobile']){echo「foo bar」;退出0;}' –

+0

不幸的是它並沒有訣竅:( – elharion

+0

)你是否在你的ajax文章中添加了'mobile'參數,並且有一些有效的數據可以傳遞'if'?嘗試將'beforeFilter'中的邏輯去掉讓控制器處理所有內容 –

回答

1

有幾件事情可以在這裏進行調試:

1 - 首先,確保您的請求達到正確的控制器功能。我注意到你的ajax函數中有url: 'Users/add',。一般情況下,這將是url: '/Users/add',或另謀出路,你叫控制器/視圖

之前,可以做簡單的測試,以確保它達到控制器視圖功能得到基本路徑:

$('.addUser').on('click', function(){ 
    var data = $('#UserAddForm').serialize();  
    $.ajax({ 
     dataType: "html", 
     type: "POST", 
     evalScripts: true, 
     url: 'Users/add', 
     data: data, 
     success: function (data){ 
      console.log(data); 
     } 
    }); 
}) 

public function add() { 
    $this->layout = 'ajax'; 
    $this->autoRender = false; 
    echo json_encode(array('this is some' => ' json data')); 
} 

2 - - 如果#1工作正常,然後開始雙重檢查您的發佈數據:

public function add() {  
     $this->layout = 'ajax';  
     $this->autoRender = false; 
     //just checking for request data because you 
     //may be doing a put and not knowing it  
     if ($this->request->data) {   
      echo json_encode($this->request->data);  
     } 
    } 

使用chrome或firefox並檢查輸出。

+0

謝謝您的回答!我會馬上檢查您的解決方案!:) – elharion

+0

請求正在到達控制器。在第二步中,數據顯示在視圖上。 我決定添加'$ this-> request-> is('ajax')' ,我的控制器沒有看到我的ajax請求。返回false。 – elharion

+0

'if($ this-> request-> is('ajax'){//其餘代碼}' 返回false – elharion