[英]Yii controller method call from view button
I've been reading a lot about this but I can't find a proper solution for my issue. 我已经阅读了很多关于此的内容,但是找不到适合我问题的解决方案。
In Yii framework, I need to execute a controller method after clicking into a button from a view . 在Yii框架中,我需要从视图中单击按钮后执行控制器方法。 I tried to do this with Javascript but it's not working.
我试图用Javascript来做到这一点,但是它不起作用。 I don't need to change anything from the view, just execute the code into the controller.
我不需要从视图中进行任何更改,只需将代码执行到控制器中即可。 Just after controllers execution is done, I have to get the return variable to show some answer on the view.
控制器执行完毕后,我必须获取return变量以在视图上显示一些答案。
AjaxButton in yii : yii中的AjaxButton :
echo CHtml::ajaxButton('ButtonName',Yii::app()->createUrl('controller/action'),
array(
'type'=>'POST',
'data'=> 'js:{"data1": val1, "data2": val2 }',
'success'=>'js:function(data){ alert(data); /* */}',
'update'=>'selectorNameToBeUpdated',
),array('class'=>'someClass',));
onclick="callController();"
Use it using ajax, create a function and call it via javascript using onclick event. 通过ajax使用它,创建一个函数,然后使用onclick事件通过javascript调用它。
<script>
function callController(){
$.post("index.php?r=controllerName/functionName, function (data) {
});
}
</script>
Finally I got a solution making a mixture of your advices. 最终,我得到了一个解决方案,结合了您的建议。 Besides, I'm working on a third party project and the code is quite confusing, actually the controller wasn't in the right directory... Anyway, this is my solution:
此外,我正在做一个第三方项目,代码很混乱,实际上控制器不在正确的目录中……无论如何,这是我的解决方案:
On my view, call to my JavaScript function 在我看来,调用我的JavaScript函数
onclick="myMethod(myVar");
then: 然后:
<script>
function myMethod(Var) {
$.ajax({
type: "POST",
url: "<? echo Yii::app()->createUrl('MyController/MyControllerMethod'); ?>",
data: {val: Var},
success: function(msg){
alert("Operation result: " + msg)
},
error: function(xhr){
alert("failure"+xhr.readyState+this.url)
}
});
}
</script>
In my controller, just did some operations and return with echo: 在我的控制器中,执行了一些操作并返回echo:
public function actionMyControllerMethod() {
// some operations
echo $result;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.