我有一个 Ext.data.TreeStore 从文本文件中读取数据:
this.store = Ext.create('Ext.data.TreeStore', {
model: "GeoExt.data.LayerTreeModel",
proxy: new Ext.data.HttpProxy({
url: 'data/test.json',
reader: {
type: 'json',
root: 'children',
idProperty: 'Id'
}
}),
folderSort: true
});
这是文件内容:
[
{
text: "Category1",
leaf: false,
expanded: true,
checked: false,
children: [
{
text: "A1",
layer: "A2",
name: "A3",
leaf: true,
checked: false,
nodeType: "gx_layer"
},
{
text: "B1",
layer: "B2",
name: "B3",
leaf: true,
checked: false,
nodeType: "gx_layer"
}
],
nodeType: "gx_layer"
},
{
text: "Category2",
leaf: false,
expanded: true,
checked: false,
children: [
{
text: "C1",
layer: "C2",
name: "C3",
leaf: true,
checked: false,
nodeType: "gx_layer"
}],
nodeType: "gx_layer"
}
]
我在 firebug 中注意到 get 不返回 JSON struct ,而是纯文本。但它有效。
我想得到相同的结果,但从 web 服务中获取树节点(这将它从 postgres 中带回来)。
我尝试的第一个最简单的事情是(也尝试过 text/json):
[WebMethod]
public void GetJSON()
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "text/plain";
HttpContext.Current.Response.Charset = "utf-8";
string res = File.ReadAllText(@"D:\test.json");
HttpContext.Current.Response.Write(res);
}
我收到错误:
Request format is unrecognized for URL unexpectedly ending in '/getJSON'.
这是有道理的,因为该文件不是 JSON(但这就是我设法使其工作的方式)。
我想帮助解决两件事:
- 我需要使用什么正确的 JSON 格式来获得与本示例中相同的结果?
- 如何从 webservice 提供相同的数据?
谢谢 !
***************** 解决方案 ******************
根据 Meister 的回答,该方法需要如下所示:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void GetJSON()
{
Object res = new Object();
JavaScriptSerializer js = new JavaScriptSerializer();
string str = js.Serialize(res);
Context.Response.Clear();
Context.Response.ContentType = "application/json";
Context.Response.AddHeader("content-disposition", "attachment; filename=export.json");
Context.Response.Flush();
Context.Response.Write(str);
}