简体   繁体   English

提交后如何防止刷新?

[英]How to prevent from refreshing after submitting?

I got this code right here which executes the function validate() when submit is clicked. 我在这里获得了这段代码,当单击提交时,它将执行validate()函数。 The function changes some of the text in the page. 该功能更改页面中的某些文本。 But I can't see the effect because the page automatically refreshes after submission: 但是我看不到效果,因为提交后页面会自动刷新:

<form name="myForm" onsubmit="validate(); return false;">
    Age: <input type="text" name="age" />
    Height (meters): <input type="text" name="height" />
    Weight (kilograms): <input type="text" name="weight" />
    <input type="submit" value="Submit">
</form>

How do I prevent the page from reloading after each submission? 如何防止每次提交后重新加载页面?

You can use a test button inside your form 您可以在表单内使用测试按钮

<input type="button" value="Test button" onclick="validate();">

Once solved, remove the button. 解决后,卸下按钮。

You can also use Firebug (or equivalent) to add a breakpoint in your javascript code. 您还可以使用Firebug(或等效工具)在JavaScript代码中添加断点。

The submit event fired by your form automatically initiates the form action. 您的表单触发的Submit事件将自动启动表单操作。 If no form action is declared, it refreshes the page. 如果未声明任何表单操作,则刷新页面。 Your need to prevent this default action from occuring before validation, then submit the data after it has passed validation. 您需要防止在验证之前发生此默认操作,然后在数据通过验证后提交数据。

Add preventDefault() to your validation code. preventDefault()添加到您的验证代码。

Make sure you add return false; 确保您添加return false; in your validate() function. 在您的validate()函数中。

That will prevent the form to be submitted. 这样将阻止提交表单。

Example : 范例:

 function validate() {
     //Validation code goes here
     return false;
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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