2016-07-18 25 views
0

我對ajax調用有問題。事實上,我正在編程一個PHP網站(cakephp框架),當彈出窗口出現時,用戶必須選擇是或否按鈕,並根據他的選擇我保存他的選擇。但我不知道爲什麼它不起作用。在cakephp中的Ajax調用

這裏是我的代碼:視圖(suivis.ctp)

<title>jQuery UI Dialog - Modal confirmation</title> 
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"> 
    <script src="//code.jquery.com/jquery-1.10.2.js"></script> 
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script> 
    <link rel="stylesheet" href="/resources/demos/style.css"> 

<script> 
$(function() { 

    // yes = 1, no = 0 
    function recordClick(val) { 
    console.log('sending...'); 

    // return ajax call, which returns a Promise object 
    return $.ajax({ 
     url: 'controller/method', 
     method: 'POST', 
     data: {the_value: val}, 
     complete: function() { 
     console.log('Data was sent!'); 
     } 
    }); 
    } 

    $("#dialog-confirm").dialog({ 
    modal: true, 
    buttons: { 

     "Oui": function() { 
     recordClick(1).then(function() { 
      $(this).dialog("close"); 
     }); 
     }, 

     "Non": function() { 
     recordClick(0).then(function() { 
      $(this).dialog("close"); 
     }); 
     } 
    } 
    }); 

}); 
</script> 


<div id="dialog-confirm" title="Confirmation de paiement"> 
    <p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>Avez vous effectué le paiement ? </p> 
</div> 

的recordClick(0)不工作我不能關閉彈出了這一點,我不明白爲什麼。也是我的URL也許是錯誤的...

,這裏是我的控制器:AccountsController.php

public function suivis() 
{ 
      if ($this->request->is('ajax')) { 
    $value_to_save = $this->request->data['the_value']; 

    if ($value_to_save == 1) { 
     $this->redirect(array('controller'=>'Accounts','action'=>'commander')); 
     $this->Commande->addsave('yes'); 
    } else { 
     $this->redirect(array('controller'=>'Accounts','action'=>'commander')); 
     $this->Commande->addsave('no'); 
    } 
    } 

謝謝你的幫助。使用

$.ajax({ 
     url: 'AccountsController.php', 
     data: {val: val}, 
     complete: function() { 
     console.log('Data was sent!'); 
     } 
    }); 

和你的PHP,值了:在你的js

+0

'url:'controller/method','這是相對於當前網址 - 即它不是固定的,並且一個潛在的直接原因是爲什麼你的代碼不工作。 – AD7six

+0

是的,我猜對了,但我試過各種URL,我們如何「撰寫」的網址?知道請求必須發送到AccountsController.php文件(suivis函數) –

+1

''/ controller/method''默認情況下。如果它有效,你發出一個重定向 - 它不會做任何事情。 「不起作用」究竟意味着什麼 - 你期望代碼做什麼,會發生什麼?請查看控制檯是否存在js錯誤,以及開發人員工具的網絡選項卡,以查看您的ajax請求正在做什麼。 – AD7six

回答

-1

試試這個

echo ($_GET['val']); 
+0

如果您不熟悉運動部件,請不要回答問題。 'url:'AccountsController.php','沒有Cakephp的版本有這樣的urls。 -1。 – AD7six

+0

我只是想幫助@ AD7six –

+0

它也無法正常工作,我必須保留recordClik函數嗎?並與回聲我收到了什麼,因爲我不知道什麼變量我會用來保存後? –

1

我認爲你是由於無效的相對URL讓你的Ajax請求未找到錯誤路徑。

在你的佈局文件 添加以下線下head標籤

<base href="<?php echo $this->Url->build('/'); ?>"> 

基礎標籤是在URL引用路徑很有幫助。這是適用於url:'控制器/方法'也在ajax中。 Refere https://developer.mozilla.org/en/docs/Web/HTML/Element/base

我希望它適合你。