Express' render/redirect does not work if the call isn't coming from a submit method in a form

落花浮王杯 提交于 2019-12-01 07:48:58

I'm not a jQuery expert, but I think the first attempt doesn't work because $.post makes an AJAX request, the same way as you would in a single-page app to interact with an API in the background.

Your second example submits a form, which is an in-browser action that performs a navigation action (as specified by the method attribute of the form). In this case, the event listener you add in jQuery is redundant, and should be removed - it's making another background POST request, before the form submits the content of its fields in its request.

As for your second question, the way to submit additional variables with a form submission (presuming that you actually want to do a navigating form submission and not an XHR background request against an API) is to use <input type="hidden"> elements.

So, to summarize, to do what you're describing in your question, your example HTML should look like this (minus the comments):

<!DOCTYPE html> <!-- only you can prevent quirks mode -->
<html>
  <head>
    <meta charset="UTF-8"> <!-- ༼ つ ◕_◕ ༽つ Give UNICODE -->
  </head>
  <body>
    <form action='/vote' method='post'>
      <input type="hidden" name="message" value="hello!">
      <button id='send' type='submit' class='btn btn-success btn-xs'>Svara</button>
    </form>
  </body>
</html>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!