简体   繁体   English

Ajax调用将字符串传递到Web服务并返回String []

[英]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#). 我是Ajax和webservices的新手,并尝试在Javascript代码中进行Ajax调用,该调用将字符串传递给我的webservice方法(C#)。 Afterwards the webservice method have to return a string array which I want to loop through in my Ajax success method. 之后,webservice方法必须返回一个字符串数组,我想在我的Ajax成功方法中循环它。 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. “ groupname”是一个字符串变量,“ data”应该是一个数组。 Any suggestions? 有什么建议么?

Should I use "text" for the contentType and is there a dataType: "String[]"? 我应该为contentType使用“文本”,并且是否有一个dataType:“ String []”?

webservice code: 网络服务代码:

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

The webservice method works. webservice方法有效。 I have tested it writing the result into a CSV file. 我已经测试过将结果写入CSV文件。 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 : 在您的Web服务中设置JSON内容类型响应标头,然后填充JSON对象:

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 : 将JSON contentType保留在您的AJAX调用中,然后在javascript中进行解析:

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

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

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