struts2, ajax and injected jquery tag

前端 未结 1 1135
既然无缘
既然无缘 2020-12-19 23:54

I am using Struts 2.3 with struts2-jQuery-plugin.

I have to load dynamically with ajax a result from an action.
In the JSP there is some normal html and a jQuer

相关标签:
1条回答
  • 2020-12-20 00:58

    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.

    0 讨论(0)
提交回复
热议问题