jquery 使用apache捕获从catch返回的json消息

nwo49xxi  于 2023-10-17  发布在  jQuery
关注(0)|答案(1)|浏览(112)

使用json捕获返回错误消息。我想显示此消息,但似乎无法捕获它。
控制器:

public ActionResult GetTable()
        {
            try
            {
               ...
            }
            catch (Exception ex)
            {
               ........
                return Json(new { result = false, message = "İşlem başarıyla gerçekleşti ancak tablo güncellenirken bir sorun oluştu." });
            }
        }

Js:

function updateTable(isInsert) {
    var pageNumber = 1;
    if (isInsert) {
        pageNumber = 1;
    } else {
        pageNumber = $('#customersTable').bootstrapTable('getOptions').pageNumber;
    }
    $.get('/Customer/GetTable', function (data) {
        $('#tableContainer').html(data);
        $('#customersTable').bootstrapTable('destroy');
        $('#customersTable').bootstrapTable();
        $('#customersTable').bootstrapTable('selectPage', pageNumber);
    })
        .fail(function (jqXHR, textStatus, errorThrown) {
            var response = jqXHR.responseText;
            showToast('Başarısız', response.message, false);
        });
}
jjhzyzn0

jjhzyzn01#

你试图访问response.message,但是response是一个字符串,你需要将它解析为JSON来访问message属性。

function updateTable(isInsert) {
    var pageNumber = 1;
    if (isInsert) {
        pageNumber = 1;
    } else {
        pageNumber = $('#customersTable').bootstrapTable('getOptions').pageNumber;
    }
    $.get('/Customer/GetTable', function (data) {
        $('#tableContainer').html(data);
        $('#customersTable').bootstrapTable('destroy');
        $('#customersTable').bootstrapTable();
        $('#customersTable').bootstrapTable('selectPage', pageNumber);
    })
    .fail(function (jqXHR, textStatus, errorThrown) {
        try {
            var response = JSON.parse(jqXHR.responseText);
            showToast('Başarısız', response.message, false);
        } catch (e) {
            // Handle the error if the response is not valid JSON
            showToast('Başarısız', 'Bir hata oluştu', false);
        }
    });
}

相关问题