Ajax button post in yii

2019-03-31 10:23发布

Can anyone give example of how to use CHtml::ajaxbutton with Yii for posting the elements without form?

标签: ajax yii
3条回答
Root(大扎)
2楼-- · 2019-03-31 11:11

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',));
?>

ajaxSubmitButton()

You need a data parameter inside the ajaxoptions

查看更多
一纸荒年 Trace。
3楼-- · 2019-03-31 11:19

To pass the data, you need to add it to your ajax array, e.g.:

<?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 dataContainer would be submitted, and could be accessed via $_POST.

Obviously, the JS could be more complicated, you could get values from certain elements, and build your own object, e.g.:

'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')

查看更多
你好瞎i
4楼-- · 2019-03-31 11:25

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>
查看更多
登录 后发表回答