在使用mvc时,向服务器端发送post请求时有时需要传递数组作为参数值,下面通过实例代码给大家介绍jquery ajax向服务端传递数组参数值的方法,一起看看吧,希望能帮助到大家。
下面使用例子说明,首先看一下action
[httppost]
public actionresult test(list<string> model)
{
return json(null, jsonrequestbehavior.allowget);
}
方式一,构造表单元素,然后调用serialize()方法得到构造参数字符串
@{
layout = null;
}
<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>test</title>
</head>
<body>
<p>
<input type="button" id="btnajax" value="发送请求" />
</p>
<script src="~/scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
var tmp = '<input type="hidden" name="model" value="1" /><input type="hidden" name="model" value="2" />';
$(function () {
$("#btnajax").click(function () {
$.ajax({
url: '@url.action("test")',
type: 'post',
data: $(tmp).serialize(),
success: function (json) {
console.log(json);
}
});
});
});
</script>
</body>
</html>
调试模式监视参数,当点击按钮时,监视得到的参数如下
方式二:使用javascript对象作为参数传值,参数名是与action方法对应的参数名,参数值是javascript数组
@{
layout = null;
}
<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>test</title>
</head>
<body>
<p>
<input type="button" id="btnajax" value="发送请求" />
</p>
<script src="~/scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
//var tmp = '<input type="hidden" name="model" value="1" /><input type="hidden" name="model" value="2" />';
var array = ["abc","123"];
$(function () {
$("#btnajax").click(function () {
$.ajax({
url: '@url.action("test")',
type: 'post',
data: {
model:array
},
success: function (json) {
console.log(json);
}
});
});
});
</script>
</body>
</html>
方式三,使用json作为参数请求,此时ajax需要声明content-type为application/json
@{
layout = null;
}
<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>test</title>
</head>
<body>
<p>
<input type="button" id="btnajax" value="发送请求" />
</p>
<script src="~/scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
//var tmp = '<input type="hidden" name="model" value="1" /><input type="hidden" name="model" value="2" />';
//var array = ["abc","123"];
$(function () {
$("#btnajax").click(function () {
$.ajax({
url: '@url.action("test")',
type: 'post',
contenttype:'application/json;charset=utf-8',
data: json.stringify({
model:["hello","welcome"]
}),
success: function (json) {
console.log(json);
}
});
});
});
</script>
</body>
</html>
上面的例子使用的是asp.net mvc 5
相关推荐:
如何用php传递数组给js脚本
jquery ajax 传递数组到后台失败的问题
jquery ajax 向后台传递数组以及如何在后台接收数组代码详解
以上就是ajax向服务端传递数组参数值实例详解的详细内容。