LoginSignup
2
2

More than 3 years have passed since last update.

REST API($.ajax)でRedmineのチケットを更新するときは、レスポンスのdataTypeをJSONにしてはならない

Posted at

概要

  • jquery(3.5.0)の$.ajax()でRedmineのチケットを更新しようとしたら、上手くいかなくて困ったので共有

事象

書いたコード

function updateTicketTitle( ticket_id, new_title ) {
    let url = `https://xxxxxx/redmine/issues/${ticket_id}.json?key=0123456789abcdef0123456789abcdef`;

    update_data = {
        "issue": {
            "subject": new_title
        }
    };

    $.ajax({
        url: url,
        type: "PUT",
        contentType: 'application/json',
        data: JSON.stringify(update_data),
        dataType: 'json'
    }).done(function(data, status, xhr) {
        console.log( "Success!!" );
    }).fail(function(xhr, status, error) {
        console.log( "Failed.." );
        console.log( {"xhr": xhr, "status": status, "error": error } );
    });
}

updateTicketTitle( "16", "New Title" );

実行結果

image.png

  • parsererrorで失敗
    • JSON inputがおかしいとのこと
  • 一方で、xhr.statusは200(成功)
    • チケットも期待通り更新されている
      • image.png

原因

  • $.ajax()dataType: 'json'を渡していたのが原因
    • チケットの更新は、サーバからのレスポンスが存在しない
      • レスポンスが存在しないのにjsonでparseしようとして失敗していた

解決方法

  • dataType: 'text'に変更する
function updateTicketTitle( ticket_id, new_title ) {
    let url = `https://xxxxxx/redmine/issues/${ticket_id}.json?key=0123456789abcdef0123456789abcdef`;

    update_data = {
        "issue": {
            "subject": new_title
        }
    };

    $.ajax({
        url: url,
        type: "PUT",
        contentType: 'application/json',
        data: JSON.stringify(update_data),
        dataType: 'text'
    }).done(function(data, status, xhr) {
        console.log( "Success!!" );
    }).fail(function(xhr, status, error) {
        console.log( "Failed.." );
        console.log( {"xhr": xhr, "status": status, "error": error } );
    });
}

updateTicketTitle( "16", "New Title" );
  • 今度は成功
    • image.png
2
2
1

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