![](/img/trans.png)
[英]How to consume WebService returned DataTable from ASP.net with PHP
[英]JSON returned from ASP.NET WebService is inadequate
我构建了几个Web服务,这些服务成功地将我的.NET类型序列化为JSON。 但是,我遇到了使JSON与YUI库特别是与DataTable完全兼容的问题。
可以使用JSON对象完全配置YUI数据表。 我在.NET中创建了以下结构来表示给定的YUI列定义:
public struct YuiColumnDefinition{
public string key;
public string label;
public bool sortable;
public string formatter;
}
'formatter'属性是您如何指示YUI表在显示给定列时使用自定义javascript函数。 问题在于,由于格式化程序定义为字符串,因此ASP.NET在序列化时将其值用双引号引起来,并且YUI不再将值识别为JavaScript令牌:
JSON YUI期望
[
{key:"1", label:"Order Date", formatter:myCustomJavaScriptFunction, sortable:true},
{key:"2", label:"Customer Name", formatter:null, sortable:false}
]
JSON ASP.NET创建
[
{key:"1", label:"Order Date", formatter:"myCustomJavaScriptFunction", sortable:true},
{key:"2", label:"Customer Name", formatter:null, sortable:false}
]
除了修改YUI源代码以外,还有其他解决方案吗?
谢谢
更改您的解析代码。
将json视为xml的替代品,您不会在xml中放置变量/函数。 在任何一种格式中,您都可以轻松确定要使用的格式化程序的名称或类型(例如从列表或枚举中获取)。 然后,您的解析代码将知道它应该将变量/方法分配为“格式器”属性。
在这样的回调中返回实际的变量/函数是不正确的。 您可以使它起作用,但老实说这不是可行的方法。
我会做以下...
将您的返回json更改为此。
[
{key:"1", label:"Order Date", formatterName:"myCustomJavaScriptFunction", sortable:true},
{key:"2", label:"Customer Name", formatterName:null, sortable:false}
]
然后在JS中,假设json存储在returnedObj
变量中
function augmentReturnedObject(returnedObj)
{
// validate that returnObj.formatterName (as a variable) is not undefined
var isValidObj = (window[returnedObj.formatterName] !== undefined);
if (isValidObj)
{
// this will return the actual function / variable, here we are assigning it to returnedObj.formatter
returnedObj.formatter = window[returnedObj.formatterName];
}
else
{
returnedObj.formatter = null;
}
}
您可以轻松地将其减少为
function augmentReturnedObject(returnedObj)
{
var specifiedMethod = window[returnedObj.formatterName];
returnedObj.formatter = (specifiedMethod === undefined) ? null : window[returnedObj.formatterName];
}
因此,最后,您将使用json对象,并进行augmentReturnedObject(returnedObj);
而在这一点上,你可以通过returnedObj
到YUI
正如艾伦正确指出的那样:
在这样的回调中返回实际的变量/函数是不正确的。
不过,我在YUI文档中找不到任何地方可以说明如何处理以JSON或XML字符串形式返回的javascript函数。
谢天谢地,博客。 如本节所述,注册自定义javascript格式设置功能的“正确”方法是使用YAHOO.widget.DataTable.Formatter:
从.ASMX返回的JSON列定义
[
{key:"1", label:"Order Date", formatter:"myCustomJavaScriptFunction1", sortable:true},
{key:"2", label:"Customer Name", formatter:null, sortable:false}
{key:"3", label:"State", formatter:"myCustomJavaScriptFunction2", sortable:false}
]
Javscript连接YUI数据表
YAHOO.widget.DataTable.Formatter.myCustomJavaScriptFunction1= this.myCustomJavaScriptFunction1;
YAHOO.widget.DataTable.Formatter.myCustomJavaScriptFunction2= this.myCustomJavaScriptFunction2;
function myCustomJavaScriptFunction1(elCell, oRecord, oColumn, oData) {
//do something
}
function myCustomJavaScriptFunction2(elCell, oRecord, oColumn, oData){
//do something
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.