简体   繁体   English

如何在不刷新整个页面的情况下提交表单

[英]How do I submit a form without refreshing the entire page

I've looked into this some time, and all examples I've found always includes text input fields and php. 我已经调查了一段时间,我发现的所有示例都包含文本输入字段和php。

I've created a community which has a "Like-button", one click shows a higher number, click again and it drops -1, it works like a charm. 我创建了一个拥有“Like-button”的社区,只需点击一下即可显示更高的数字,再次点击它会下降-1,它就像一个魅力。 But I don't like the refresh part, it messes everything up and starts at the top. 但是我不喜欢刷新部分,它会把一切都弄糟,从顶部开始。

I've tried tons of Ajax/Jquery coding but can't prevent the "reload part". 我已经尝试了大量的Ajax / Jquery编码,但无法阻止“重装部分”。 I don't know if I have any code to post since I never save any of the worthless codes that never works. 我不知道我是否有任何代码要发布,因为我从来没有保存任何无用的代码。

However, the form starts like this and includes the "submit-image": 但是,表单就像这样开始并包含“submit-image”:

@using (Ajax.BeginForm("Like", "Home", FormMethod.Post, null, new { id = "LikeForm" }))
{
...
<input type="image" src="../Images/star.png" name="submit" />
...
}

The result is presented in a nearby. 结果显示在附近。

Everything is sent to the ActionResult Like() that saves everything in the database. 一切都被发送到ActionResult Like() ,它保存了数据库中的所有内容。 The result is later presented in the View . 结果稍后在视图中显示 Nothing unusual about that part I hope. 我希望那部分没什么不寻常的。

Once again, I've looked into many examples and none worked for me, my main page for information was at http://api.jquery.com/ and stackoverflow. 再一次,我看了很多例子,没有一个对我有用,我的主要信息页面是http://api.jquery.com/和stackoverflow。 Nothing gained in this case. 在这种情况下没有任何进展。

If your attempted to do it using jQuery before, I expect that your code looked something like this: 如果您之前尝试使用jQuery,我希望您的代码看起来像这样:

$('#LikeForm').on('submit', function() {
  // do AJAX stuff here
});

This is already close enough, just missing the part where it prevents the form from still being submitted the traditional way. 这已经足够接近,只是错过了它阻止表单仍然以传统方式提交的部分。 If you still haven't tried so, try doing it like this: 如果您还没有尝试过,请尝试这样做:

$('#LikeForm').on('submit', function(e) {
  e.preventDefault();
  // do AJAX stuff here
});

What it does is that it prevents the default behavior of the form element (which is, to submit itself with a page reload), and just do the AJAX stuff. 它的作用是它阻止了表单元素的默认行为(也就是说,通过页面重新加载来提交自己),并且只是执行AJAX的东西。

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

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