开发者

Returning json in asp.net webservice

开发者 https://www.devze.com 2023-03-20 07:36 出处:网络
In my application,we use the prototype1.4.2 in the page. 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

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

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

It is built based on the prototype.

And there is a function:

onopenpopulate:

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

Called after a branch is opened. When it's open, it launch an Ajax request at the page openlin开发者_如何学编程k 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

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

I always get the xml format.

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

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?


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"};
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号