我正在尝试使用jQuery Ajax将字符串参数数组传递给C#ASP.NET Web服务。这是我的示例Web方法。请注意,该函数接受可变数量的参数。运行jquery时,我在Chrome的JavaScript控制台中收到500 Internal Server Error。我正在使用jquery 1.6.2和.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:
$(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>
任何帮助表示赞赏!
修改后的服务器端代码:
[WebMethod] public string Concat(List<string> arr) { string result = ""; for (int i = 0; i < arr.Count; i++) { result += arr[i]; } return result; }
另外,在WebService类声明上方添加以下内容:
WebService
[System.Web.Script.Services.ScriptService]
修改后的客户端代码:
$(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的引用,例如:
<script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
笔记:
public string Concat(List<string> **_arr_** )
data: JSON.stringify({ **_arr_** : myCars })