日期:2014-05-17  浏览次数:20467 次

求教:AJAX向后台WebMethod static方法传递数组并接收
就是前台传一个数组到后台,然后后台的WebMethod static方法直接接收这个数组并使用!不想用那种传统的Requset 方法接收 还得一个个分割 好麻烦!求各位大侠简单明了的指点一下吧 谢谢谢了!
AJAX? jquery? ?asp.net ?webmethod

------解决方案--------------------
看下这个例子:

<script src="http://code.jquery.com/jquery-1.10.1.js"></script>
<script>
$(document).ready(function () {
var myCars = new Array();
myCars[0] = "Saab";
myCars[1] = "Volvo";
myCars[2] = "BMW";

$.ajax({
type: "POST",
url: "<%=Request.Url.AbsolutePath%>/Concat",
data: JSON.stringify({ arr: myCars }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
             alert(response.d);
},
failure: function () {
             alert("fail");
}
});
});
</script>

[System.Web.Script.Services.ScriptService]
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}

[WebMethod]
public static string Concat(List<string> arr)
{
string result = "";
for (int i = 0; i < arr.Count; i++)
{
result += arr[i];
}
return result;
}
}

------解决方案--------------------
你要是传递字符串数组可以改用直接传递字符串,将字符串以特定的形式组织,后台进行分割处理。