且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过javascript将POST请求发送到REST API

更新时间:2022-11-27 22:39:50

您的代码存在的问题是,您不是在拦截"代码.表单的Submit事件,因此它将执行默认行为,即默认行为 POST (因为它没有告诉它去哪里的指令).除非您有机会停止这种默认行为,否则表单将执行此操作.

The problem with your code is that you are not "intercepting" the submit event of your form so it will execute the default behavior which is POST to itself (since it doesn't have an instruction that tells it where to go). Unless you can have a chance to stop this default behavior, the form will perform this action.

要拦截表单的Submit事件,您必须告诉浏览器注意该事件并执行自定义函数,而不是使用如下所示的事件侦听器:

To intercept the form's submit event you have to tell the browser to watch out of this event and execute a custom function instead of using an event listener like below:

<script>

document.getElementById('whatever-form-id')
  .addEventListener('submit', check);

function check(e) {
  e.preventDefault();
  // and now anything else you want to do.
}

</script>

这将阻止您的表单发布,而将执行您的功能.

This will prevent your form from posting and it will execute your function instead.