struts2, ajax and injected jquery tag

纵饮孤独 提交于 2019-11-29 12:07:11
Andrea Ligios

The problem is that struts2-jQuery-plugin is generating a script that will run after the DOM is ready: jQuery(document).ready(function () { ...

After the page is rendered, the ready event is fired. But after an AJAX call, it is not.

Then you have two solutions:

  1. avoid using struts2-jquery-plugin for the JSP snippet that is returned by AJAX; use instead plain jQuery and avoid using jQuery(document).ready(function () {
    (but I guess it won't be completely reliable);

  2. use a trick to override the default jQuery ready event, as described in this great answer, so that the ready function will become triggerable.
    Then trigger it as last row of your JSP snippet returned by AJAX

    <sj:datepicker cssClass="dataScadenzaDiv" id="dataScadenzaDiv"
                   name="dataScadenza"        maxDate="-1d" 
                   label="data scadenza"      theme="xhtml"/>
    <script>
         $.triggerReady();
    </script>
    

I've made a fiddle showing the trick, and tested it in jQuery 1.10.1:

Running demo

HTML

<input type = "button" 
      value = "trigger ready event" 
    onclick = "$.triggerReady();" />

JAVASCRIPT

// Overrides jQuery-ready and makes it triggerable with $.triggerReady
// This script needs to be included before other scripts using the jQuery-ready.
// Tested with jQuery 1.10.1
(function(){
var readyList = [];

// Store a reference to the original ready method.
var originalReadyMethod = jQuery.fn.ready;

// Override jQuery.fn.ready
jQuery.fn.ready = function(){
if(arguments.length && arguments.length > 0 && typeof arguments[0] === 'function') {
  readyList.push(arguments[0]);
}

// Execute the original method.
originalReadyMethod.apply( this, arguments );
};

// Used to trigger all ready events
$.triggerReady = function() {
  $(readyList).each(function(){this();});
};
})();


/* This part is for demo only and should be removed */
$( document ).ready(function(){
    alert('document.ready is fired!');
});

Remember that also the other handlers originally run in ready event will be triggered again, so use this with caution.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!