在asp.net webservice中返回json [英] Returning json in asp.net webservice

查看:20
本文介绍了在asp.net webservice中返回json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my application,we use the prototype1.4.2 in the page.

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

And we need the tree view which support lazy load(make a ajax request and add the data from the server to the node),then I found the

TafelTree

它是基于原型构建的.

还有一个函数:

onopenpopulate:

它会根据用户提供的openlink"从服务器加载数据.

It will load data from the server according the "openlink" provided by user.

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

Called after a branch is opened. When it's open, it launch an Ajax request at the page openlink and send the Ajax response to the user function. It must return a JSON string representing an array of one or more TafelTreeBranch. Override setOnOpenPopulate() of TafelTree

但是需要服务端返回纯json数据格式.

But it need the server return pure json data format.

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

And I have created a webservice this way:

[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'}";
    }
}

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

However when I invoke this service use:

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

我总是得到 xml 格式.

I always get the xml format.

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

Through google,it seems that I have to set the "content-type" when make the ajax request.

但是,就我而言,ajax 是由TafelTree"发送的,我无法添加额外的参数.

However,in my case,the ajax is sent by the "TafelTree",I can not add extra parameters.

有什么想法吗?或者使用另一个基于原型的树?

Any idea? or use another prototype based tree?

推荐答案

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

you can use jquery to do an Ajax call.

$.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)
{
}

注意不一定要返回字符串,可以返回对象列表.

Note that it is not necessarily to return a string, you can return a list of 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"};
    }
}

这篇关于在asp.net webservice中返回json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆