LoginSignup
1
1

More than 1 year has passed since last update.

ajaxが通信成功しているのにfailで処理される場合の対処方法

Posted at

原因

ajaxの通信が成功しているのに、thenではなくfailで処理されてしまう現象が発生した。

調査した結果、以下の4行目のdataTypeを指定しないと、jQueryのほうでjson形式に自動で変換しようするため、パースエラーが発生してfailに入ってしまう。

jsファイル
$.ajax({
  type: "post",
  url: "/api/test/done-test",
  dataType: "text", // ここでデータ型を指定しないとjsonで処理されてparsererrorになる
  data: {
    sampleData: 'sample',
  },
})
//通信成功
.then((res) => {
  console.log('成功');
})
//通信失敗
.fail((xhr, textStatus, errorThrown) => {
  console.log(textStatus);
  console.log('失敗');
});

対策

レスポンスのデータ型dataTypeを適切に指定する。

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