來自網絡,自己測試過;可以用
前台:
<script type="text/javascript">
function CSmethod() {
$.ajax({ type: "Post",
url: "javaTest.aspx/HelloWorld",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{days:2}",
success:function (data) { alert(data.d); },
error: function (err) { alert(err); }
});
}
</script>
后台:
[System.Web.Services.WebMethod]
public static string HelloWorld(Int32 days)
{
// return "Hello World of CS1";
return "[{\"nowtime\":\"" + DateTime.Now.AddDays(days).ToShortDateString() + "\"}]";
}
前台發送數組:
<script type="text/javascript">
function AddNewWork() {
var js_Arr = new Array(); //定義數組
js_Arr.push("{ name: '張三', salary: '50' }, { name: '李四', salary: '60' }, { name: '王五', salary: '70' }");
$.ajax({ type: "Post",
url: "MyPage.aspx/AddNewWork",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{arr_Str:[" + js_Arr + "]}", //傳送數組
success: function (data) { alert(data.d); },
error: function (err) { alert(err); }
});
}
后台接收數組
[System.Web.Services.WebMethod]
public static ArrayList AddNewWork(Dictionary<string, string>[] arr_Str)
{
// return "Hello World of CS1";
// return "[{\"nowtime\":\"" + DateTime.Now.AddDays(days).ToShortDateString() + "\"}]";
ArrayList al = new ArrayList();//創建動態數組
al.Add("{張三:'10'}");
al.Add("{李四:'20'}");
al.Add("{王五:'30'}");
al.Add("{趙六:'40'}");
return al;//返回動態數組
}
如果要js_Arr是一個數組,那么可以直接使用
data: {"str_Fc_Id": js_Arr}
jQuery會幫助進行序列化。