LoginSignup
4
3

More than 5 years have passed since last update.

ajax読み込みでFailed to load resource: the server responded with a status of 412 (Precondition Failed)が出る場合

Last updated at Posted at 2015-06-11

Safariのajax読み込みでPrecondition Failedになる場合


発生状況

jqueryの$.ajaxで以下のようにデータを取得している場合


    $.ajax({
        url: "hoge.json",
        method: 'POST',
        dataType: 'json',
    })
    .done(function(data) {
        //do something
    })
    .fail(function() {
        console.log( "error" );
    })
    .always(function() {
        //do something
    });


発生するエラー

[Error] Failed to load resource: the server responded with a status of 412 (Precondition Failed) (hoge.json, line 0)


直し方

$.ajaxのbeforeSendで時間を指定してあげれば良い。
確認しているなかで、safariがヒットする。iOSのサファリも出るのかな。


    $.ajax({
        url: "hoge.json",
        method: 'POST',
        dataType: 'json',
        //以下追加
        //再現している環境がsafariのみなので、安易にsafariのみ判定
        beforeSend : function( xhr ){
            if (window.navigator.userAgent.toLowerCase().indexOf('safari') != -1)
                xhr.setRequestHeader("If-Modified-Since", new Date().toUTCString());
        }                
    })


なんで治るのかというか、そもそもなんのエラーなのか

リクエストヘッダーの以下の値の評価がfalseになってしまうらしい←

(リクエストヘッダーって、なんぞ、っていう。。
すみません、詳しい方いたら補足もらえると嬉しいっす。)

  • If-Match
  • If-None-Match
  • If-Unmodified-Since

ということで、そのうちの1つ、If-Unmodified-Sinceに最新データを渡してあげて、最新データと認識させてあげる。



調べると、chromeでもエラー出てるケースもあるみたいで、果たしてこの方法が良いのか悪いのか。

・・・

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