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

Ext JS API POST数据已入库但Success函数未执行问题求助

问题:Ext JS表单POST请求成功入库但触发Failure回调

使用ASP.NET Web API作为后端,Ext JS作为前端UI。点击保存按钮触发POST请求后,数据已成功存入数据库,但前端的Success函数未执行,仅Failure函数被触发,日志也仅显示Failure执行。


前端Grid JS代码

tbar: [
{
  text: "Add Movie",
  iconCls: "fa fa-plus",
  handler: function () {
    Ext.create("Ext.window.Window", {
      title: "Add Movie",
      modal: true,
      items: [
        {
          xtype: "form",
          bodyPadding: 10,
          defaultType: "textfield",
          defaults: {
            anchor: "100%",
            labelWidth: 100,
          },
          items: [
            {
              fieldLabel: "Name",
              name: "name",
              allowBlank: false,
            },
            {
              fieldLabel: "Description",
              name: "description",
              xtype: "textarea",
              allowBlank: false,
            },
            {
              fieldLabel: "Available",
              name: "available",
              xtype: "numberfield",
              allowBlank: false,
              regex: /^[0-9]+$/,
              regexText: "Only numeric values are allowed",
            },
          ],
          buttons: [
            {
              text: 'Save',
              formBind: true,
              handler: function () {
                var form = this.up('form').getForm();
                if (form.isValid()) {
                  console.log('Before form submit');
                  form.submit({
                    url: 'https://localhost:44345/api/movies',
                    method: 'POST',
                    success: function (form, action) {
                      console.log('Success: ', action.response.responseText);
                      try {
                        var jsonData = JSON.parse(action.response.responseText);
                        console.log('Valid JSON:', jsonData);
                        Ext.Msg.alert('Success', 'Movie saved successfully');
                        form.reset();
                      } catch (error) {
                        console.log('Invalid JSON:', error);
                        Ext.Msg.alert('Error', 'Invalid JSON response');
                      }
                    },
                    failure: function (form, action) {
                      console.log('Failure: ', action.response.responseText);
                      Ext.Msg.alert('Error', 'Failed to save the movie');
                    }
                  });
                }
              }
            },
            {
              text: "Cancel",
              handler: function () {
                this.up("window").close();
              },
            },
          ],
        },
      ],
    }).show();
  },
},

后端API POST方法代码

public IHttpActionResult Post([FromBody] Movies movieDto)
{
    if (!ModelState.IsValid)
        return BadRequest(ModelState);

    var movie = new Movies
    {
        Name = movieDto.Name,
        Description = movieDto.Description,
        Available = movieDto.Available
        // Set other properties as needed
    };

    _dbContext.Movies.Add(movie);
    _dbContext.SaveChanges();

    // Return the created movie with its assigned ID
    movieDto.Id = movie.Id;
    return Created(Request.RequestUri + "/" + movieDto.Id, movieDto);
}

解决方案

1. 调整后端响应格式以符合Ext JS要求

Ext JS的form.submit()默认要求后端返回的JSON必须包含success字段(值为true/false),即使HTTP状态码是201(Created),如果响应中没有该字段,会判定为失败并触发Failure回调。

修改后端返回逻辑,将响应包装为包含success字段的结构:

public IHttpActionResult Post([FromBody] Movies movieDto)
{
    if (!ModelState.IsValid)
        return BadRequest(ModelState);

    var movie = new Movies
    {
        Name = movieDto.Name,
        Description = movieDto.Description,
        Available = movieDto.Available
    };

    _dbContext.Movies.Add(movie);
    _dbContext.SaveChanges();

    movieDto.Id = movie.Id;
    // 返回带success字段的响应
    return Ok(new {
        success = true,
        data = movieDto
    });
}

如果需要保留201状态码,可改用Created方法返回包装后的对象:

var response = new {
    success = true,
    data = movieDto
};
return Created(Request.RequestUri + "/" + movieDto.Id, response);

2. 调试确认响应细节

在前端Failure回调中添加更多日志,明确失败原因:

failure: function (form, action) {
    console.log('Failure类型:', action.failureType);
    console.log('响应状态码:', action.status);
    console.log('响应内容:', action.response.responseText);
    Ext.Msg.alert('Error', 'Failed to save the movie');
}

常见的失败类型包括:Ext.form.action.Action.CONNECT_FAILURE(连接错误)、Ext.form.action.Action.SERVER_INVALID(服务器返回无效响应)等,可快速定位问题。

3. 前端自定义成功判断逻辑(可选)

如果无法修改后端代码,可在Ext JS的提交配置中自定义成功判定规则,比如通过HTTP状态码判断:

form.submit({
    url: 'https://localhost:44345/api/movies',
    method: 'POST',
    success: function (form, action) {
        // 原有成功逻辑
    },
    failure: function (form, action) {
        // 若状态码为201,视为成功
        if (action.status === 201) {
            console.log('通过状态码判定成功');
            var jsonData = JSON.parse(action.response.responseText);
            Ext.Msg.alert('Success', 'Movie saved successfully');
            form.reset();
            return;
        }
        // 原有失败处理
        console.log('Failure: ', action.response.responseText);
        Ext.Msg.alert('Error', 'Failed to save the movie');
    },
    // 自定义成功属性判断函数
    successProperty: function(response) {
        return response.status === 200 || response.status === 201;
    }
});

内容的提问来源于stack exchange,提问作者Rey Chabby Estrera

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 11:57:50