How to call a javascript function once on page load, page reloads, don't call it again

我与影子孤独终老i 提交于 2019-12-04 06:18:39

问题


On a Magento shopping cart, there are 2 forms that need to be filled out: shipping estimate and coupon code. Each refreshes the page after submitting the form. The shipping estimate form needs to be submitted before the coupon form so that the coupon can validate the country.

What I'd like to do is to call the shipping form's coShippingMethodForm.submit() on load. That way the country is loaded, and then the coupon form will check the country. This has the added advantage that the initial shipping rates are displayed without requiring the user to submit the form.

My challenge: if I call coShippingMethodForm.submit() on load - it will refresh the page and then continuously refresh b/c the coShippingMethodForm.submit() keeps submitting and refreshing.

How do I call that function once, page refreshes, and not run again (unless the user clicks the submit button).

Example Magento cart page I'm referring to


回答1:


You can use cookie to prevent resumbit on reload.
Function js for broswer cookie can be found here http://www.quirksmode.org/js/cookies.html
In your JS function coShippingMethodForm.submit

coShippingMethodForm.submit = function(){
     //check cookie here
     if(readCookie('already_submit')==1)
          return;
     createCookie('already_submit', 1, 1); //for 1 day
     //old code here
}

And on submit button, add eraseCookie line:

<input type="submit" id="your_submit_button" 
       onclick="eraseCookie('already_submit');" />



回答2:


I see you're using PHP, why not just have a hidden form <input type='hidden' name='countrySubmitted' value='true' /> and then when php renders the page check to see if the value is set, if not then call the function to submit.

echo "<script type='text/javascript'>";
if (isset($_POST['countrySubmitted']))
echo "document.coShippingMethodForm.Submit();";
echo "</script>";


来源:https://stackoverflow.com/questions/3455532/how-to-call-a-javascript-function-once-on-page-load-page-reloads-dont-call-it

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