我是网络编程新手,在 Cakephp 中使用 javascript (jquery) 时遇到问题。 事实上,我在 jquery 中使用弹出窗口(对话框),并且根据用户单击的结果必须在数据库中注册,所以我认为我必须将结果提供给 Controller 。 我不知道如何在不使用表单的情况下将值从 View 传递到 Controller 。 例如,当用户单击对话框中的"is"按钮时,我想注册此数据。 我把我的代码放在下面,谢谢。
//view.ctp
<script>
$(function() {
$( "#dialog-confirm" ).dialog({
modal: true,
buttons: {
"Oui": function() {
$( this ).dialog( "close" );
},
"Non": 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>
最佳答案
由于事件发生在客户端 (javascript),因此您需要通过 AJAX 将数据 POST 到 Controller 方法(这也很方便,因为您已经在使用 jQuery)。
JS代码
$(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" );
});
}
}
});
});
蛋糕2.x代码
<?php
public function method() {
// Run only if this is an AJAX request and we are POSTing data
if ($this->request->is('ajax') && !empty($this->request->data)) {
$value_to_save = $this->request->data['the_value'];
if ($value_to_save == 1) {
$this->Controller->save('yes');
} else {
$this->Controller->save('no');
}
} else {
throw new \MethodNotAllowedException('This method is not allowed');
}
}
如果没有看到你的 Controller 方法和一切,这很困难,但这或多或少是你想要的。
<小时/>所以从高的 Angular 来看:
- 在模式中单击按钮时,调用 JS 函数,并根据您单击的内容传入参数(“1”表示"is",“0”表示“否”)。
- 该函数向某个 Controller 方法发出 AJAX 请求,并将从其参数接收到的数据传递到 AJAX 调用的
data
属性中。 - 您的 Controller 方法将通过
$this->request->data
访问该数据,在本例中,我们将其作为the_value
传递。 - 在您的 Controller 方法中,获得数据后,使用您通常使用的任何方式将其保存到数据库中。
关于javascript - 在 cakephp 中使用 javascript 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38146520/