简体   繁体   中英

Passing variable from JavaScript to PHP and reload DIV/iframe

I have a website which contains an iframe within a DIV. The width of the iframe should be dependent on the width of the browser.

Therefore I'm using a JavaScript function and a EventListener to get the width of the browser. That works fine.

Now I have to pass the determined width from JavaScript to my iframe and reload it. This is my HTML/PHP code with the iframe of the index.html :

<div id="scout">
    <?php
        $iframeWidth = "<script>document.write(iframeWidthFromJS)</script>";
        echo "iframe width is " . $iframeWidth;
    ?>

    <iframe src="http://cpcms.scout" width="<?php echo $iframeWidth; ?>" height="600"></iframe>
</div>

And this is my JavaScript, which does not work:

window.addEventListener('resize', getWindowSize);
window.onload(getWindowSize());

function getWindowSize()
{
    var iframeWidthFromJS = 800;

    if (typeof (window.innerWidth) == 'number')
    {
        // Get current browser width
        width = window.innerWidth;
        iframeWidthFromJS = width;

        alert(iframeWidthFromJS);

        // Reload the DIV to apply new iframe width
        $( "#scout" ).load(window.location.href + " #scout" );
    }
}

Determining the width works, but not passing it to the iframe.

不能只使用width="100%"

modify your code in such a way that the parent div containing your iframe also gets the new width

<?php
            $iframeWidth = "<script>document.write(iframeWidthFromJS)</script>";
            echo "iframe width is " . $iframeWidth;
        ?>

    <div id="scout" width="<?php echo $iframeWidth; ?>">
        <iframe src="http://cpcms.scout" width="<?php echo $iframeWidth; ?>" height="600"></iframe>
    </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM