JQuery Ajax Plugin for ColdFusion Developers

I wrote a plugin to provide all of my popular default ColdFusion, such as:

  • returnFormat = JSON
  • queryFormat = column
  • type = 'after'
  • DATATYPE = 'JSON'
  • .fail ()
  • .done () (but with a catch)

It works, but I don’t know why I should use

myXHR = $.fn.myAjax() 

instead

 myXHR = $.myAjax() 

Here is the code:

 !function($) { $.extend( $.fn, { myAjax: function(myURL, settings) { var local = {}; $('#msg').empty().removeClass('alert alert-info'); local.settings = $.extend({}, $.fn.ajaxDefaults, settings); local.myURL = myURL + '?returnFormat=json&queryFormat=column' local.result = $.ajax(local.myURL,local.settings) local.result.done(function(result) { if (result.MSG) { $('#msg').html(result.MSG).addClass('alert alert-info'); } }); local.result.fail(function(A,B,C) { $('#msg').html(C).addClass('alert alert-info'); }); return local.result; }, ajaxDefaults:{ type: 'POST', dataType: 'json', async:false // todo: context = this } } ) $('input[type=checkbox]').bind('change', function(myEvent, ui) { var settings = {}; settings.data = {}; settings.data.PersonID = $(this).val(); settings.context = this; if ($(this).is(':checked')) { settings.data.method = 'check'; myXHR = $.fn.myAjax('Evnt.cfc',settings); myXHR.done(function(result) { if (!result.MSG) { log(result.QRY.DATA); } }); } else { settings.data.method = 'uncheck'; myXHR = $.fn.myAjax('Evnt.cfc',settings); myXHR.done(function(result) { if (!result.MSG) { log(result.QRY.DATA); } }); } }); }(jQuery); 
+4
source share
1 answer

You essentially set up your plugin as follows:

 ( function($) { $.fn.doSomething = function() { // stuff }; }(jQuery)); 

... and therefore there is a plugin that works with jQuery objects. So this will work:

 $('#something').doSomething(); 

But you call it like this:

 $.doSomething(); // doesn't work 

Since you obviously want your function to stand alone in the jQuery namespace, you would set it like this:

 $.doSomething = function(){ // stuff }; 

So, in the case of your code, try adding this below, right above the end of your function:

 $.myAjax = $.fn.myAjax; 

As a side note, it is not recommended to use more than one namespace for your plugin ( ajaxDefaults from your example). You should quickly read the jQuery 's Create Plugin page for some useful tips.

+3
source

Source: https://habr.com/ru/post/1402064/


All Articles