我使用 Model.save
保存 ExtJs 表单中的数据。有时服务器会返回以下格式的操作状态:
{"success": false, "error": {"name": "Invalid Name"}}
以下代码将数据从表单发送到服务器:
var model = formPanel.getRecord(); model.save({ callback: function(record, operation, success) { // operation.response is null, // and success === true // how to read server response here? } })
服务器响应被视为成功,因为 HTTP 状态为 200。所以我必须读取服务器响应来检查操作状态。但是 callback
函数中的 operation.response
为 null
。
这是我的模型:
Ext.define('My.Model', { extend: 'Ext.data.Model', idProperty: 'id', fields: [ {name: 'id', type: 'auto'}, {name: 'name', type: 'auto'} ], proxy: { type: 'rest', url: 'api/v1/models', appendId: true, reader: { type: 'json', }, writer: { type: 'json' } } });
问题:调用 Model.save
后如何访问服务器响应?
更一般的问题:使用 Model.load
或 Model.save
填充/保存 ExtJs 表单在语义上是否正确?
我使用的是 ExJs 5.0.1.1255。
最佳答案
我为此创建了一些简单的测试代码:
var Clazz = Ext.define('MyModel', {
extend: 'Ext.data.Model',
proxy: {
type: 'rest',
url: 'api/v1/models'
}
});
var instance = Ext.create('MyModel', {
name: 'MyName'
});
instance.save({
callback: function(record, operation) {
}
});
服务器响应:
{
success: true,
something: 'else'
}
您可以在此处的 fiddle 中看到这一点:https://fiddle.sencha.com/#fiddle/fhi
使用此代码,回调有一个 record
参数,并且 record.data
包含与服务器响应合并的原始记录。此外,您可以执行 operation.getResponse()
(而不仅仅是 operation.response
)来获得对服务器响应的完全访问权限。
关于加载与保存的问题,如果您使用 View 模型并以这种方式绑定(bind)模型,那么它就变得毫无意义,因为您的表单应该始终反射(reflect)模型的状态。
关于ExtJs5:如何在 Model.save 中读取服务器响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27626172/