prevent page from reloading after form submit

廉价感情. 提交于 2019-12-13 00:42:12

问题


Is there a way to detect and stop if page is reloading.

I have a page which is getting reloaded after successful submission of a form present in it. I want to have an event listener which sees if page is reloading and should stop it from being reloaded.

I cannot return false; for sucessful submit of registration form


回答1:


In your html:

<form onsubmit="myFunction()"> Enter name: <input type="text"> <input type="submit"> </form>

In your javascript:

myFunction = function(e) { // prevents default action to happen e.preventDefault(); // do what ever you want to do here // i.e. perform a AJAX call }




回答2:


You would have to submit the form using AJAX to avoid refreshing the entire page.

This can be accomplished with regular Javascript but is made easier with jQuery http://api.jquery.com/jquery.ajax/




回答3:


Detecting if the page is reloading is a very dirty solution.

You have to prevent the default action

<script>
$( "a" ).click(function( event ) {
  event.preventDefault();
});
</script>

http://api.jquery.com/event.preventdefault/




回答4:


In that case you'll need to implement the form sending mechanics via some kind of AJAX call.

Because sending a form is actually loading a new page with some parameters (which are the form data).




回答5:


Here's how a standard form submission works:

Browser -> issues GET or POST HTTP request -> Server
Browser <- returns the result of the request <- Server
Browser re-renders the current page based on the server's response.

Therefore, a standard form submit will always incur a page reload.

However, you can use AJAX to make your HTTP request, which allows you to avoid a page reload.

Have a look at $.ajax




回答6:


The default action after submit is to send to the page where it manipulates the data. if you are trying to stop the refresh, i.e you are not submitting the form.

  1. stop the form from default submitting using e.preventDefault(). this will stop the default submit behavior, which includes reload of page[ but form is not submitted]
  2. you have to submit the form using AJAX in background [your data is submitted in the background to the required page]


来源:https://stackoverflow.com/questions/27018422/prevent-page-from-reloading-after-form-submit

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