2017-07-03 90 views
-1

我被交給一個用cakePhp框架編寫的項目,需要添加一些額外的功能。我試圖遵循現有的語法,但不知何故無法獲得新的功能。Ajax調用cakePhp不會執行請求的控制器中的php代碼

原始視圖文件下面的腳本部分(HTML東西后):

<script type="text/javascript"> 

function printorderpage() { 
    window.print(); 
} 

</script> 

我想要做的是執行某些數據庫操作(標記記錄爲鎖定下來,它可以不再當用戶打印頁面時被編輯)。

這就是我添加到視圖文件:

(function() { 
    var beforePrint = function() { 
     //console.log('Functionality to run before printing.'); 
     //alert('before print test'); 
    }; 
    var afterPrint = function() { 
     //console.log('Functionality to run after printing'); 
     alert('lock'+<?=$order_id?>); 

     $.ajax({ 
      url: "/Workorder/ajaxLockOrder/<?=$order_id?>?debug=false", 
      type: "post", 
      dataType: "json", 
      data: post_data 
     }).done(function(e) { 
      alert(e.message); 
     }); 

     alert('done?'); 

    }; 

    if (window.matchMedia) { 
     var mediaQueryList = window.matchMedia('print'); 
     mediaQueryList.addListener(function(mql) { 
      if (mql.matches) { 
       beforePrint(); 
      } else { 
       afterPrint(); 
      } 
     }); 
    } 

    window.onbeforeprint = beforePrint; 
    window.onafterprint = afterPrint; 
}()); 

基本上打印後函數被調用時用戶打印的頁面,而這反過來又調用控制器功能「ajaxLockOrder」執行的一些數據庫操作後端。通過使用警告框,我可以驗證afterPrint功能是否已執行(警報彈出窗口成功顯示需要鎖定的$ order_id,在我的測試案例中,order_id是「18」,警示框顯示爲「lock18」) 。但那麼ajaxLockOrder沒有被調用?

控制器文件名爲「workorder_controller.php」,這裏的控制器內部的ajaxLockOrder功能:

function ajaxLockOrder($order_id) { 
    //once the order is printed, lock the order so it can not be changed 
    error_log("executed", 3, "lockerr.log"); 
    $this->Order->updateActivityStream($order_id, 5); //data operation 
} 

通過使用的error_log功能,我可以驗證此功能並沒有因爲日誌文件執行沒有被創建。另一方面,當我試圖在瀏覽器窗口中直接輸入該函數地址(http://myurl/Workorder/ajaxLockOrder/18)時,它在後端工作並生成了日誌文件,並更新了訂單#18的數據庫記錄。爲什麼?

在此先感謝您的幫助。

回答

0
$.ajax({ 
     url: "<?php echo $this->Html->url(array('controller'=>'Workorder','action'=>'ajaxLockOrder',$order_id));?>", 
     type: "post", 
     dataType: "json", 
     data: post_data 
    }).done(function(e) { 
     alert(e.message); 
    }); 
+0

謝謝,但它沒有奏效。有了這個URL,它甚至不會執行腳本 - 甚至不會出現警告框。語法錯了嗎? – sdssrr

0

我知道這一定很簡單。原來這個特定的視圖頁面沒有加載jquery庫(可能是因爲它之前不需要任何ajax調用)。我添加了jquery庫,一切正常!

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
相關問題