简体   繁体   English

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

[英]Returning json in asp.net webservice

In my application,we use the prototype1.4.2 in the page.在我的应用程序中,我们在页面中使用prototype1.4.2。

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

TafelTree塔菲尔树

It is built based on the prototype.它是基于原型构建的。

And there is a function:还有一个function:

onopenpopulate:

It will load data from the server according the "openlink" provided by user.它将根据用户提供的“openlink”从服务器加载数据。

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.当它打开时,它会在页面 openlink 上发起一个 Ajax 请求,并将 Ajax 响应发送给用户 function。 It must return a JSON string representing an array of one or more TafelTreeBranch.它必须返回一个 JSON 字符串,表示一个或多个 TafelTreeBranch 的数组。 Override setOnOpenPopulate() of TafelTree覆盖 TafelTree 的 setOnOpenPopulate()

But it need the server return pure json data format.但它需要服务器返回纯 json 数据格式。

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

I always get the xml format.我总是得到 xml 格式。

Through google,it seems that I have to set the "content-type" when make the ajax request.通过谷歌,似乎我在发出 ajax 请求时必须设置“内容类型”。

However,in my case,the ajax is sent by the "TafelTree",I can not add extra parameters.但是,在我的情况下,ajax 是由“TafelTree”发送的,我无法添加额外的参数。

Any idea?任何想法? or use another prototype based tree?还是使用另一个基于原型的树?

you can use jquery to do an Ajax call.您可以使用 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)
{
}

Note that it is not necessarily to return a string, you can return a list of object.注意不一定要返回字符串,可以返回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