Submit form and stay on same page?

匿名 (未验证) 提交于 2019-12-03 02:01:02

问题:

I have a form that looks like this

and I would like to stay on the same page, when Submit is clicked, but still have receiver.pl executed.

How should that be done?

回答1:

The easiest answer: jQuery. Do something like this:

$(document).ready(function(){    var $form = $('form');    $form.submit(function(){       $.post($(this).attr('action'), $(this).serialize(), function(response){             // do something here on success       },'json');       return false;    }); }); 

If you want to add content dynamically and still need it to work, and also with more than one form, you can do this:

   $('form').live('submit', function(){       $.post($(this).attr('action'), $(this).serialize(), function(response){             // do something here on success       },'json');       return false;    }); 


回答2:

99% of the time I would use XMLHttpRequest or fetch for something like this. However, there's an alternative solution which doesn't require javascript...

You could include a hidden iframe on your page and set the target attribute of your form to point to that iframe.

  

There are very few scenarios where I would choose this route. Generally handling it with javascript is better because, with javascript you can...

  • gracefully handle errors (e.g. retry)
  • provide UI indicators (e.g. loading, processing, success, failure)
  • run logic before the request is sent, or run logic after the response is received.


回答3:

The HTTP/CGI way to do this would be for your program to return an HTTP status code of 204 (No Content).



回答4:

When you hit on the submit button, the page is sent to the server. If you want to send it async, you can do it with ajax.



回答5:

Just use: action="". There's no need for anything like javascript.



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