我對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
'url:'controller/method','這是相對於當前網址 - 即它不是固定的,並且一個潛在的直接原因是爲什麼你的代碼不工作。 – AD7six
是的,我猜對了,但我試過各種URL,我們如何「撰寫」的網址?知道請求必須發送到AccountsController.php文件(suivis函數) –
''/ controller/method''默認情況下。如果它有效,你發出一個重定向 - 它不會做任何事情。 「不起作用」究竟意味着什麼 - 你期望代碼做什麼,會發生什麼?請查看控制檯是否存在js錯誤,以及開發人員工具的網絡選項卡,以查看您的ajax請求正在做什麼。 – AD7six