You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET MVC 5中Ajax请求500错误:success与fail回调均不执行

问题分析与解决方案

1. 错误回调参数名错误

你在$.ajax配置里写的fail是无效的,jQuery的Ajax配置选项中,错误回调的参数名是error,而非fail。fail是jQuery Deferred对象的方法,需要通过链式调用使用。

修正方式一:改用error回调

function getSpeTemplate() {
    var tempId = $('#ddlTemplates :selected').val();

    $.ajax({
        type: 'GET',
        url: '/WhatsMessage/GetTemplate?idx=' + tempId,
        dataType: "json",
        success: function (data) {
            alert("Success Okay");
            if (data !== null) {
                $('#rowTemplateData').css("display", "block");
                $('#templateNameSend').html(data.TemplateName);
            }
        },
        // 将fail替换为error
        error: function (xhr, textStatus, errorThrown) {
            alert('request failed: ' + textStatus);
        }
    });
}

修正方式二:使用链式调用的done()和fail()

function getSpeTemplate() {
    var tempId = $('#ddlTemplates :selected').val();

    $.ajax({
        type: 'GET',
        url: '/WhatsMessage/GetTemplate?idx=' + tempId,
        dataType: "json"
    })
    .done(function (data) {
        alert("Success Okay");
        if (data !== null) {
            $('#rowTemplateData').css("display", "block");
            $('#templateNameSend').html(data.TemplateName);
        }
    })
    .fail(function (xhr, textStatus, errorThrown) {
        alert('request failed: ' + textStatus);
    });
}

2. 移除GET请求多余的contentType设置

GET请求没有请求体,contentType是用来告知服务器请求体的格式,这个设置完全多余,甚至可能导致jQuery处理响应时出现异常,直接删除即可。

3. 验证服务器返回的JSON格式有效性

确保服务器返回的是标准有效的JSON,比如:

  • 没有多余的逗号(如数组最后一项后的逗号)
  • 字符串统一使用双引号
  • 无语法错误

可以在浏览器开发者工具的「网络」面板中查看响应内容,复制后用本地编辑器的JSON校验功能验证格式是否正确。如果JSON格式错误,jQuery会解析失败并触发错误回调。

4. 可选:禁用缓存(若存在缓存问题)

如果浏览器缓存了GET请求导致响应非最新,可在$.ajax配置中添加cache: false:

$.ajax({
    type: 'GET',
    url: '/WhatsMessage/GetTemplate?idx=' + tempId,
    dataType: "json",
    cache: false, // 禁用缓存
    // ... 其他回调配置
})

内容的提问来源于stack exchange,提问作者MrMustafa022

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 19:17:16