简体   繁体   中英

JavaScript onload function loop

Currently, I have a JavaScript function that submits a form on page load, the problem, is that this function never stop, it get in a loop for ever, I'm trying to stop it when condition is met but for some reason it doesn't work.

the condition is when i==1 but it keeps going for ever.

<script type="text/javascript">
var i = 0;
function loadit(){
if (i==1){
    return;
    }else{
        document.frm.submit();
        i++
    }
}
</script>

</head>

<body onload="loadit()">

The reason for the loop is that you are reseting i back to 0 at each load time (thus, your loop), you need to store the i somewhere else, that checks if the form has been submitted, and then increases by increments.

So this would be a simple example using PHP. It will look for the i value in the URL param, under i=? . If it's not set, then automatically set it to 0.

<?php
// this will check for the i in the URL, if it's not there, set $i to 0
$i = (isset($_GET['i']) ? urlencode($_GET['i']) : 0)
?>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">

    $(function loadit() {
        // set `i` to `$i`
        var i = <?= $i; ?>;
        var frm = $('#form');
        var con = $('#content');

        if (i == 1) {
            return true;
        } else {
            frm.submit();
            i++;
        }
    });
</script>

</head>

<body onload="loadit()">

<!-- increment $i for the action field. -->
<form id="form" action="?i=<?= ++$i; ?>" method="post">

    <input id="content" type="hidden" value="Something_here">

</form>


</body>

Another method is to use Ajax, and use the response to determine whether or not it needs to be submitted again.

you submit a form so its refresh your page and then it hits the onload again. if you want the form to get submitted every time the page load do is with ajax.

you can test it by removeing the document.frm.submit(); and do console.log.

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