yii 中的 Ajax 按钮帖子
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13837333/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ajax button post in yii
提问by Anantha
Can anyone give example of how to use CHtml::ajaxbuttonwith Yii for posting the elements without form?
谁能举例说明如何使用CHtml::ajaxbuttonYii 发布没有表单的元素?
回答by arun
Quick Example
快速示例
<?php
echo CHtml::ajaxSubmitButton('ButtonName',Yii::app()->createUrl('advert/LoadAdvertFromSay'),
array(
'type'=>'POST',
'data'=> 'js:{"data1": val1, "data2": val2 }',
'success'=>'js:function(string){ alert(string); }'
),array('class'=>'someCssClass',));
?>
You need a dataparameter inside the ajaxoptions
你需要一个data参数里面ajaxoptions
回答by ernie
To pass the data, you need to add it to your ajax array, e.g.:
要传递数据,您需要将其添加到 ajax 数组中,例如:
<?php
echo CHtml::ajaxSubmitButton('ButtonName',Yii::app()->createUrl('advert/LoadAdvertFromSay'),
array(
'type'=>'POST',
'data'=> 'js:$("#dataContainer").serialize()',
'success'=>'js:function(string){ alert(string); }'
),array('class'=>'someCssClass',));
?>
In this case, all input type elements in the element with id dataContainerwould be submitted, and could be accessed via $_POST.
在这种情况下,带有 id 的元素中的所有输入类型元素dataContainer都将被提交,并且可以通过 $_POST 访问。
Obviously, the JS could be more complicated, you could get values from certain elements, and build your own object, e.g.:
显然,JS 可能更复杂,您可以从某些元素中获取值,并构建自己的对象,例如:
'data' => 'js:{"field1": $("#input1").val(), "pageTitle": $("title").text() }'
Then, in your controller, you could access $_POST["field1"]and $_POST["pageTitle"], though I generally tend to access items via CHttpRequest::getParam()as then I can get either POST or GET values, e.g. CHttpRequest::getParam('field1')
然后,在您的控制器中,您可以访问$_POST["field1"]and $_POST["pageTitle"],尽管我通常倾向于通过CHttpRequest::getParam()访问项目,然后我可以获得 POST 或 GET 值,例如CHttpRequest::getParam('field1')
回答by Truongnq
More examples of Yii ajax button
echo CHtml::ajaxButton(
$label = 'Click me',
$url = '/',
$ajaxOptions=array (
'type'=>'POST',
'dataType'=>'json',
'success'=>'function(html){ jQuery("#your_id").html(html); }'
),
$htmlOptions=array ()
);
//Output
<a href="#" id="yt0">Click me</a>
<script type="text/script">
jQuery('body').on('click', '#yt0', function () {
jQuery.ajax({
'type': 'POST',
'dataType': 'json',
'success': function (html) {
jQuery("#your_id").html(html);
},
'url': '/',
'cache': false,
'data': jQuery(this).parents("form").serialize()
});
return false;
});
});
</script>

