8
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[jQuery] フォームをJSONにしてPOSTする

Last updated at Posted at 2017-07-24

あらまし

jQueryを使って、HTMLのフォームでsubmitボタンを押したときにAjaxでPOSTするコードをここにメモしておく。

コード

$('#postForm').submit((event) => {
  $.post({
    url: "/path/to/post",
    data: $('#postForm').serialize(), // ここで#postFormをもっかい書くのやだなあ
    success: () => { console.log('success'); },
    dataType: 'json',
  })
  event.preventDefault();
})

preventDefault()しておかないと、普通にPOSTも走ってページ遷移してしまうようだ(試してない)。

追記

// ここで#postFormをもっかい書くのやだなあ

コメント頂きましたが、$(event.currentTarget)と書けるようです。
やったね!

参考

8
9
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?