intpp/yii-ajax-action

Yii的Ajax方法操作动作

1.0.10 2015-08-17 23:08 UTC

This package is not auto-updated.

Last update: 2024-09-28 16:15:26 UTC


README

使用方法

  1. 为Ajax动作创建类(例如:SiteAjaxAction)
namespace your\namespace\here;

use intpp\yii\actions\AjaxAction;

class SiteAjaxAction extends AjaxAction
{
    /**
     * @param string $name
     * @param int $age
     * @param string $gender
     * @param array $hobbies
     */
    public function getFormattedInfo($name, $age, $gender = 'male', array $hobbies)
    {
        $this->setOutput('result', true);
        $this->setOutput('text', implode(', ', [
            'Your name is ' . $name,
            'age: ' . $age,
            'gender: ' . $gender,
            'hobbies: ' . implode(', ', $hobbies)
        ]));
    }
}
  1. 将其包含在您的控制器中
    public function actions()
    {
        return [
            // Other included actions
            'ajax' => 'your\namespace\here\SiteAjaxAction',
        ];
    }
  1. 在您的JS应用程序中使用

3.1 在您的视图或布局文件中设置包含Ajax动作URL的JS变量,例如

    $ajaxUrl = Yii::app()->createUrl('/site/ajax');
    Yii::app()->clientScript->registerScript('ajaxUrl', "var ajaxUrl='{$ajaxUrl}';");

3.2 在您的JS应用程序中,您可以使用该变量进行Ajax请求,例如

    $(document).on('click', 'a#getInfo', function() {
        $.ajax({
            url: ajaxUrl,
            data: {
                method: 'getFormattedInfo', // <---- Name of a function in your AjaxAction class
                name: 'Vasya', age: 12, hobbies: ['sport', 'dev', 'sex'] // <---- Parameters for the function
            },
            dataType: 'JSON',
            success: function(response) {
                if(response.result === true) {
                    alert(response.text);
                }
            }
        });
    });

附言:其他示例在examples目录中 =)