主要問(wèn)題在返回的結(jié)果 result 標(biāo)記對(duì)應(yīng)的數(shù)據(jù)是字符串,請(qǐng)看以下官方例子中返回的數(shù)據(jù):
代碼如下:
{"type":"rpc","tid":2,"action":"Sample","method":"SaveForm","result":"{/"firstName/":/"4/",/"lastName
/":/"4/",/"age/":4}"}
“ result ”標(biāo)記對(duì)應(yīng)的是一個(gè)字符串,而不是對(duì)象,這就需要在處理數(shù)據(jù)時(shí)先要將字符串轉(zhuǎn)換成 JSON 對(duì)象才能繼續(xù)處理。這會(huì)造成使用 DirectStore 作為 Grid 數(shù)據(jù)源時(shí)取不到數(shù)據(jù)的問(wèn)題。在官網(wǎng)論壇找了一下,有個(gè)例子是重寫(xiě) Ext.data.DirectProxy 的 createCallback 方法實(shí)現(xiàn)的,其目的就是在獲取到數(shù)據(jù)后,將 result 中的數(shù)據(jù)轉(zhuǎn)換為對(duì)象再返回?cái)?shù)據(jù)。以下是重寫(xiě) createCallback 方法的代碼:
代碼如下:
Ext.override(Ext.data.DirectProxy, {
createCallback: function(action, reader, cb, scope, arg) {
return {
callback: (action == 'load') ? function(result, e) {
if (typeof result == 'string') {
result = Ext.decode(result);
}
if (!e.status) {
this.fireEvent(action + "exception", this, e, result);
cb.call(scope, null, arg, false);
return;
}
var records;
try {
records = reader.readRecords(result);
}
catch (ex) {
this.fireEvent(action + "exception", this, e, result, ex);
cb.call(scope, null, arg, false);
return;
}
this.fireEvent(action, this, e, arg);
cb.call(scope, records, arg, true);
} : function(result, e) {
if (typeof result == 'string') {
result = Ext.decode(result);
}
if (!e.status) {
this.fireEvent(action + "exception", this, e);
cb.call(scope, null, e, false);
return;
}
this.fireEvent(action, this, result, e, arg);
cb.call(scope, result, e, true);
},
scope: this
}
}
});
例子可以到以下地址下載: http://xiazai.Vevb.com/200906/yuanma/Direct.rar
不過(guò)筆者的想法是能不能在服務(wù)器端解決這個(gè)問(wèn)題。在 Ext.Direct.dll 的源代碼中,筆者找到 DirectResponse 類(lèi)的“ Result ”的定義類(lèi)型是一個(gè) object ,于是筆者在例子中將客戶端調(diào)用的方法的返回?cái)?shù)據(jù)類(lèi)型修改為 JObject ,但是在執(zhí)行以下語(yǔ)句的時(shí)候會(huì)出現(xiàn)錯(cuò)誤:
return JsonConvert .SerializeObject(response);
看來(lái)這里需要修改一下,于是筆者將 DirectProcessor 類(lèi)中的以上這句修改為以下代碼:
代碼如下:
if (response.Result.GetType().ToString() == "Newtonsoft.Json.Linq.JObject" )
{
JObject o = new JObject (
new JProperty ("type" ,response.Type),
new JProperty ("tid" ,response.TransactionId),
new JProperty ("action" ,response.Action),
new JProperty ("method" ,response.Method),
new JProperty ("result" ,(JObject )response.Result)
);
return o.ToString();
}
else
{
return JsonConvert .SerializeObject(response);
}
其作用就是如果“ Result ”屬性中的數(shù)據(jù)是“ JObject ”對(duì)象,程序就重新構(gòu)造一個(gè) JObject 對(duì)象再組合成字符串返回,如果不是就按原方法返回。