简体   繁体   中英

Ajax call passing string to webservice and getting String[] back

I'm new to Ajax and webservices and trying to make an Ajax call in my Javascript code which pass a string to my webservice method (C#). Afterwards the webservice method have to return a string array which I want to loop through in my Ajax success method. Do anyone know how to realize that?

My not working attempt:

$.ajax({
    type: "POST",
    url: "MyWebService.asmx/getMembers",
    data: groupname,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data) {
        alert("Success");
        for (var i = 0; i < data.length; i++) {
            alert(JSON.parse(data[i]));
        }
    }
});

"groupname" is a string variable and "data" should be an array. Any suggestions?

Should I use "text" for the contentType and is there a dataType: "String[]"?

webservice code:

    [WebMethod]
    public String[] getMembers(String groupname)
    {
        ...
        return userArray;
    }

The webservice method works. I have tested it writing the result into a CSV file. So the Problem must be the parameter or the return value.

Warning : cannot test.

Server side

Set a JSON content-type response header in your webservice and populate a JSON object :

private class Payload
{
    public String[] payload;
}    
...
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string getMembers(String groupname)
{
    ...
    Payload p = new Payload();
    // populate
    return new JavaScriptSerializer().Serialize(p); 
}

Check by calling your webservice if you have something like this :

{"payload":["string1","string2","string3"]}

Client side

Keep the JSON contentType in your AJAX call then parse it in javascript :

...
success: function(data) {
    alert("Success");
    for (var i = 0; i < data.payload.length; i++) {
        alert(data.payload[i]);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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