传递字符串数组来WEBMETHOD与使用jQuery AJAX可变数量的参数 [英] Passing array of strings to webmethod with variable number of arguments using jQuery AJAX
问题描述
我想要的字符串参数数组传递给使用jQuery Ajax的一个C#ASP.NET Web服务。这里是我的示例web方法。注意,函数接受可变数量的参数。我得到了Chrome的JavaScript控制台500内部服务器错误,当我运行的jQuery。我使用jQuery 1.6.2和.NET3.5
I'm trying to pass an array of string parameters to a C# ASP.NET web service using jQuery Ajax. Here is my sample web method. Note that the function accepts a variable number of parameters. I get a 500 Internal Server Error in Chrome's javascript console when I run the jquery. I'm using jquery 1.6.2 and .NET3.5
[WebMethod]
public string Concat(params string[] arr)
{
string result = "";
for (int i = 0; i < arr.Length; i++)
{
result += arr[i];
}
return result;
}
下面是jQuery的:
Here is the jquery:
$(document).ready(function() {
var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
$.ajax({
type: "POST",
url: "WebService.asmx/Concat",
data: {arr: myCars}, //can't figure out what to put here
success: onSuccess,
Error: onError
});
});
function onSuccess()
{
alert("testing");
}
function onError()
{
alert("fail");
}
</script>
任何帮助是AP preciated!
Any help is appreciated!
推荐答案
修订服务器端code:
Revised server-side code:
[WebMethod]
public string Concat(List<string> arr)
{
string result = "";
for (int i = 0; i < arr.Count; i++)
{
result += arr[i];
}
return result;
}
此外,添加这上面你的的WebService
类的声明:
[System.Web.Script.Services.ScriptService]
修订的客户端code:
Revised client-side code:
$(document).ready(function () {
var myCars = new Array();
myCars[0] = "Saab";
myCars[1] = "Volvo";
myCars[2] = "BMW";
$.ajax({
type: "POST",
url: "WebService.asmx/Concat",
data: JSON.stringify({ arr: myCars }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: onSuccess,
failure: onError
});
});
function onSuccess(response) {
alert(response.d);
}
function onError() {
alert("fail");
}
此外,添加上面的脚本阻止参考JSON2,如:
Also, add above that script block a reference to JSON2, such as:
<script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
注:
- 在我已经在.NET 4中,并使用jQuery 1.6.4测试这一点。
- 确保您保留在客户端和服务器的变量名同步:
公共字符串连接(名单&LT;字符串&GT; 改编的)
数据:JSON.stringify({ 改编的:myCars})
- I have tested this under .NET 4 and using jQuery 1.6.4.
- Make sure you keep the client and server variable names in sync:
public string Concat(List<string> arr)
data: JSON.stringify({ arr: myCars })
这篇关于传递字符串数组来WEBMETHOD与使用jQuery AJAX可变数量的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!