阻止HTML表單提交跳轉(zhuǎn)頁面,使用 Jquery Ajax 請(qǐng)求接口

作者:辰風(fēng)沐陽 閱讀:2152 發(fā)布時(shí)間:2021-04-12 上次更新:2021-04-13

1. HTML 表單


  1. <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  2. <form action="" method="post" onsubmit="return save(this)">
  3. 手機(jī)號(hào) <input type="text" name="mobile" autocomplete="off">
  4. 登錄密碼 <input type="text" name="password" autocomplete="off">
  5. <button>提交</button>
  6. </form>

2. Javascript 函數(shù)


  1. /**
  2. * 提交表單
  3. */
  4. function save(obj)
  5. {
  6. var formData = {};
  7. var array = $(obj).serializeArray();
  8. $.each(array, function() {
  9. formData[this.name] = this.value;
  10. });
  11. console.log(formData)
  12. $.ajax({
  13. url: '',
  14. type: 'post',
  15. async: false,
  16. data: formData,
  17. success: res => {
  18. console.log(res)
  19. }
  20. })
  21. return false;
  22. }

標(biāo)簽: HTML Jquery