Dae*_*Dae 17 rest extjs extjs4
我正在构建ExtJs 4的RESTFul Store示例.当Add或Delete请求失败时,我希望我的脚本显示REST服务器提供的错误.我已设法获取请求的成功状态(请参阅下面的代码),但我如何获得响应提供的消息?
商店:
var store = Ext.create('Ext.data.Store', {
model: 'Users',
autoLoad: true,
autoSync: true,
proxy: {
type: 'rest',
url: 'test.php',
reader: {
type: 'json',
root: 'data',
model: 'Users'
},
writer: {
type: 'json'
},
afterRequest: function(request, success) {
console.log(success); // either true or false
},
listeners: {
exception: function(proxy, response, options) {
// response contains responseText, which has the message
// but in unparsed Json (see below) - so I think
// there should be a better way to reach it than
// parse it myself
console.log(proxy, response, options);
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
典型的REST响应:
"{"success":false,"data":"","message":"VERBOSE ERROR"}"
Run Code Online (Sandbox Code Playgroud)
也许我做错了,所以任何建议都表示赞赏.
mis*_*cko 26
我假设您的服务遵循REST原则并使用HTTP状态代码而不是2xx不成功的操作.但是,Ext 不会为没有返回状态的响应解析响应正文2xx.在这种情况下,异常/响应对象(传递给"异常"事件侦听器)确实提供的只是HTTP状态消息response.statusText.
因此,您必须自己将responseText解析为JSON.这不是一个真正的问题,因为它可以用一条线完成.
var data = Ext.decode(response.responseText);
Run Code Online (Sandbox Code Playgroud)
根据您的编码风格,您可能还需要添加一些错误处理和/或区分"预期"和"意外"HTTP错误状态代码.(这是来自Ext.data.reader.Json)
getResponseData: function(response) {
try {
var data = Ext.decode(response.responseText);
}
catch (ex) {
Ext.Error.raise({
response: response,
json: response.responseText,
parseError: ex,
msg: 'Unable to parse the JSON returned by the server: ' + ex.toString()
});
}
return data;
},
Run Code Online (Sandbox Code Playgroud)
出现这种情况的原因可能是因为REST代理类不是数据包中的第一类成员.它派生自一个公共基类,它还定义了标准AJAX(或JsonP)代理的行为,该代理仅将HTTP状态代码用于通信通道错误.因此,在这种情况下,他们不期望来自服务器的任何可解析消息.预计将返回指示应用程序错误的服务器响应,其中HTTP状态为OK,并且在您的问题中发布了JSON响应(使用success:"false"和message:"[your error message]").
有趣的是,REST服务器可以返回具有非2xx状态的响应和具有有效JSON响应的响应主体(在Ext术语中),并且success属性设置为"true".异常事件仍将被触发,并且未解析响应主体.这个设置没有多大意义 - 我只是想指出HTTP状态代码与成功属性(第一个优先于后者)之间的'成功'之间的区别.
对于更透明的解决方案,您可以扩展(或覆盖)Ext.data.proxy.Rest:这会将成功值更改false为true,然后调用标准的processResponse实现.这将模拟"标准"Ext行为并解析responseText.当然,这将期望您原始帖子中列出的标准JSON响应success:"false"(或以其他方式失败).这是未经测试的,if表达式可能应该更智能.
Ext.define('Ext.ux.data.proxy.Rest', {
extend: 'Ext.data.proxy.Rest',
processResponse: function(success, operation, request, response, callback, scope){
if(!success && typeof response.responseText === 'string') { // we could do a regex match here
var args = Array.prototype.slice.call(arguments);
args[0] = true;
this.callParent(args);
} else {
this.callParent(arguments);
}
}
})
Run Code Online (Sandbox Code Playgroud)