[英]How to stay on same position after submitting an html form?
我有一个简单的html形式:
<form action="addToCart" method="post"><br><br>
<input name="productId"
value="${product.id}" type="hidden"> <input class="submit" onclick="addedCart()" value="<fmt:message key='AddToCart'/>"
type="submit">
</form>
每次单击“提交”,都会使我直接回到顶部,这会带来糟糕的用户体验,因为用户必须向下滚动浏览产品的位置...我可以不使用脚本来做到这一点吗?
如果您想实现自己想要的目标,那么Ajax是您最好的选择
$('.submit').on('click',function(event){
event.preventDefault(); //this is important else page will get submitted
$.ajax({
url:'where you want to process data',
dataType:'html',
data: your form data as json or whatever type
success: function(result){
//here you can update any thing on the frontside
}
});
});
-每次我点击“提交”时,都会直接回到顶部。
是的,这是提交表单时的默认功能,它始终重新绘制dom,以便引起跳转并呈现页面的顶部位置。
-这会带来糟糕的用户体验,因为用户必须向下滚动浏览产品的位置
为了获得良好的用户体验,您可以使用ajax来实现此功能,因为您在问题中标记了jQuery,然后可以尝试使用jquery ajax:
$('form').submit(function(e){
e.preventDefault(); // stops the form submission
$.ajax({
url:$(this).attr('action'), // action attribute of form to send the values
type:$(this).attr('method'), // method used in the form
data:$(this).serialize(), // data to be sent to php
dataType:"text",
success:function(data){
alert(data); // you can alert the success message.
},
error:function(err){
console.log(err);
}
});
});
我已经使用了dataType:"text",
只是假设您是否要echo "Added in the cart.";
来自php的消息。
由于您在按钮上使用onclick
属性,因此必须将type
属性从submit
更改为button
。 这样一来,您就可以addedCart()
方法。 然后在该方法内处理表单提交(如果您的提交处理程序尚不存在)。
<input class="submit" onclick="addedCart()" value="<fmt:message key='AddToCart'/>" type="button">
脚本:
function addedCart(){
// ... your method on click
// $.ajax({...});
};
如果您不使用jQuery,则可以使用XMLHttpRequest
处理表单提交:
如何在没有jQuery的情况下进行AJAX调用?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.