【发布时间】:2016-07-18 09:25:29
【问题描述】:
我对 ajax 调用有疑问。事实上,我正在用 php(cakephp 框架)编写一个网站,当弹出窗口出现时,用户必须在是或否按钮之间进行选择,并且根据他的选择,我正在保存他的选择。但我不知道为什么它不起作用。
这是我的代码:视图 (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) 不起作用我无法用它关闭弹出窗口,我不明白为什么。另外我的网址可能是错误的......
这是我的控制器: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');
}
}
感谢您的帮助。
【问题讨论】:
-
url: 'controller/method',与当前 url 相关 - 即它不是固定的,也是您的代码无法正常工作的一个潜在直接原因。 -
是的,我猜是这样,但我尝试了各种 URL,我们如何“组合”URL?知道请求必须发送到 AccountsController.php 文件(suivis 函数)
-
'/controller/method'默认情况下。如果它有效,您将发出重定向 - 这不会做任何事情。 “不起作用”到底是什么意思 - 你期望代码做什么,会发生什么?请查看控制台是否有 js 错误,以及您的开发人员工具的网络选项卡以查看您的 ajax 请求在做什么。 -
不起作用意味着代码不会像我在下面的 js 部分中用按钮解释的那样,如果我们单击“是”,则 val 应该等于 1,如果不是,则为 0函数 recordClick 没有被“调用”。应该发生什么:首先应该关闭弹出窗口,然后应该将 val 的值发送到控制器并保存,但没有发生任何事情。如果我不清楚,我很抱歉
-
“不做任何事情”没有澄清......任何事情。代码被调用了吗?它会产生错误吗?代码是否已加载?请不要写cmets,edit the question添加信息。祝你好运。