yii.captcha.js 1.62 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
/**
 * Yii Captcha widget.
 *
 * This is the JavaScript widget used by the yii\widgets\Captcha widget.
 *
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
(function ($) {
	$.fn.yiiCaptcha = function (method) {
		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error('Method ' + method + ' does not exist on jQuery.yiiCaptcha');
			return false;
		}
	};

	var defaults = {
		refreshUrl: undefined,
		hashKey: undefined
	};

	var methods = {
		init: function (options) {
			return this.each(function () {
				var $e = $(this);
				var settings = $.extend({}, defaults, options || {});
				$e.data('yiiCaptcha', {
					settings: settings
				});

				$e.on('click.yiiCaptcha', function() {
					methods.refresh.apply($e);
					return false;
				});

			});
		},

		refresh: function () {
			var $e = this,
				settings = this.data('yiiCaptcha').settings;
			$.ajax({
				url: $e.data('yiiCaptcha').settings.refreshUrl,
				dataType: 'json',
				cache: false,
				success: function(data) {
54 55
					$e.attr('src', data.url);
					$('body').data(settings.hashKey, [data.hash1, data.hash2]);
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
				}
			});
		},

		destroy: function () {
			return this.each(function () {
				$(window).unbind('.yiiCaptcha');
				$(this).removeData('yiiCaptcha');
			});
		},

		data: function() {
			return this.data('yiiCaptcha');
		}
	};
})(window.jQuery);