PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

Ajax向服务端传递数组参数值实例详解

小云云
小云云 原创
2017-12-29 11:24:29 3793浏览

在使用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向服务端传递数组参数值实例详解的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。