繁体   English   中英

在 asp.net 网络服务中返回 json

[英]Returning json in asp.net webservice

在我的应用程序中,我们在页面中使用prototype1.4.2。

我们需要支持延迟加载的树视图(发出 ajax 请求并将来自服务器的数据添加到节点),然后我找到了

塔菲尔树

它是基于原型构建的。

还有一个function:

onopenpopulate:

它将根据用户提供的“openlink”从服务器加载数据。

在分支打开后调用。 当它打开时,它会在页面 openlink 上发起一个 Ajax 请求,并将 Ajax 响应发送给用户 function。 它必须返回一个 JSON 字符串,表示一个或多个 TafelTreeBranch 的数组。 覆盖 TafelTree 的 setOnOpenPopulate()

但它需要服务器返回纯 json 数据格式。

我以这种方式创建了一个网络服务:

[WebService(Namespace = "http://microsoft.com/webservices/";
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class UtilService: WebService {
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string loadData(id) {
      //some logic according the id
      return "{id:0,name:'xx'}";
    }
}

但是,当我调用此服务时,请使用:

http://xxx/UtilService/loadData?id=0

我总是得到 xml 格式。

通过谷歌,似乎我在发出 ajax 请求时必须设置“内容类型”。

但是,在我的情况下,ajax 是由“TafelTree”发送的,我无法添加额外的参数。

任何想法? 还是使用另一个基于原型的树?

您可以使用 jquery 进行 Ajax 调用。

$.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "webServiceUrl/MethodName",
        data: "{Id: '" + id + "'}",
        dataType: "json",
        success: loadSucceeded,
        error: loadFailed,
        async: true
    });

function loadSucceeded(result, status)
{
    var data = result.d;
}

function loadFailed(result, status)
{
}

注意不一定要返回字符串,可以返回object的列表。

[WebService(Namespace = "http://microsoft.com/webservices/";
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class UtilService: WebService 
{
    [WebMethod]
    public List<string> loadData(id) {
      //some logic according the id
      return new List<string>(){"data"};
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM