3
3

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.

Fetch APIを使ってjQuery.ajaxみたいにデータをpostする

Last updated at Posted at 2017-05-04

まとめ

URLSearchParamsを使うとできる

jQueryの場合

以下のようにhogefooを送りたいとする。

jquery.js
$.ajax({
      url: '/api/tasks',
      type: 'POST',
      data: {hoge: 'fuga', foo: 'bar'},
});

jq.png

Fetch APIの場合

URLSearchParamsを使う

以下のようにbodyにURLSearchParamsを入れると、Content-Typeも適切に設定される

fetch1.js
let params = new URLSearchParams()
params.set('hoge', 'fuga')
params.set('foo', 'bar')
fetch('/api/tasks', {
    method: 'POST',
    credentials: 'include',
    body: params,
})

fetch1.png

直接文字列として書く

ヘッダを設定する必要があるので注意

fetch('/api/tasks', {
    method: 'POST',
    credentials: 'include',
    headers: {
        "Content-Type": "application/x-www-form-urlencoded"
    },
    body: 'hoge=fuga&foo=bar',
})

fetch2.png

3
3
0

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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?