Iframe adaptive height problem resolution in jquery ajax applications

  • 2020-03-30 02:35:22
  • OfStack

The iframe adaptive height itself is a simple way to recalculate the height once the page is loaded.

The code is as follows:


//Public method: sets the height of the iframe to ensure that all data is displayed
//function SetPageHeight() {
//    var iframe = getUrlParam('ifname');
//    var myiframe = window.parent.document.getElementById(iframe);
//     iframeLoaded(myiframe);
//}
var iframeLoaded = function (iframe) {
    if (iframe.src.length > 0) {
        if (!iframe.readyState || iframe.readyState == "complete") {
            var bHeight = 
            iframe.contentWindow.document.body.scrollHeight;
            var dHeight = 
            iframe.contentWindow.document.documentElement.scrollHeight;
            var height = Math.max(bHeight, dHeight);
            iframe.height = height;
        }
    }
}
//Reset the iframe height when paging; Modified: iframe.name = iframe.id
var reSetIframeHeight = function()
{
    try {
        var oIframe = parent.document.getElementById(window.name);
        oIframe.height = 100;
        iframeLoaded(oIframe);
    }
    catch (err)
    {
        try {
         parent.document.getElementById(window.name).height = 1000;
          } catch (err2) { }
    }
}

Call reSetIframeHeight (); The method is ok.

However, there is another case where jquery ajax is used to request data. The data is still making HTTP requests after the body load is completed. At this time, no data occupies the height of the window, and reSetIframeHeight method cannot calculate the height.

At this point, we came up with a method: when will the ajax Complete? Of course, the Complete event is Complete.

But we also can't add processing to the ajax Complete event on every page. This is where jquery ajax's global variables are used.

Code to handle ajax and iframe adaptation:

var sendcount = 0;
var completecount = 0;
//Add ajax global event handling.
reSetIframeHeight();
$(document).ajaxStart(function (a, b, c) {
}).ajaxSend(function (e, xhr, opts) {
    sendcount++;
}).ajaxError(function (e, xhr, opts) {
}).ajaxSuccess(function (e, xhr, opts) {
}).ajaxComplete(function (e, xhr, opts) {
    completecount++; 
        reSetIframeHeight();

}).ajaxStop(function () {
});

Execute reSetIframeHeight, and then call reSetIframeHeight after each ajax finish.


Related articles: