使用 AJAX 将列表作为参数发送

send list as a parameter with ajax

本文关键字:参数 AJAX 列表 使用      更新时间:2023-09-26

我想使用 ajax 发送一个列表作为参数,但在我的函数参数中为 null。 我可以用 JSON 解决这个问题,但 IE 7 不支持 JSON.这是我的代码。 我该如何解决这个问题????

 $(function () {
     $('#DeleteUser').click(function () {
         var list = [];
         $('#userForm input:checked').each(function () {
             list.push(this.id);
         });
         $.ajax({
             url: '@Url.Action("DeleteUser", "UserManagement")',
             data: {
                 userId: list
             },
             type: 'POST',
             success: function (result) {
                 alert("success");
             },
             error: function (result) {
                 alert("error!");
             }
         }); //end ajax
     });
 });

我找到了答案。查看此站点 http://bestiejs.github.io/json3/

添加 Douglas Crockford 著名的 json2.js,并使用功能检测来填充 polyfill json 序列化以实现兼容性

https://github.com/douglascrockford/JSON-js

从文档:

JSON.stringify(value, replacer, space)
value       any JavaScript value, usually an object or array.
replacer    an optional parameter that determines how object
            values are stringified for objects. It can be a
            function or an array of strings.
space       an optional parameter that specifies the indentation
            of nested structures. If it is omitted, the text will
            be packed without extra whitespace. If it is a number,
            it will specify the number of spaces to indent at each
            level. If it is a string (such as ''t' or ' '),
            it contains the characters used to indent at each level.

建议的代码更改:

{ ... data: JSON.stringify(list) ... }

这可能有几个原因导致此操作失败

从代码来看,您似乎正在使用剃须刀。如果这不是在剃刀视图中(即.cshtml文件),您的链接将不正确。

如果链接正确,则假设控制器设置正确,代码将起作用。由于数据不是 URL 的一部分,因此您需要为 userId 参数指定FromBody

public ActionResult DeleteUser([FromBody] userId){
    //implementation
}

或者,您可以将列表附加到 URL

url: '@Url.Action("DeleteUser", "UserManagement")/' + list 

当然,在global.asax中有一个路由,它将第一个参数发送到userId