Jquery 向后端传数组问题

148 阅读1分钟
1. 问题

使用jQuery.ajax向后端传数组时,后端接受不到

2. 原因

因为jQuery需要调用jQuery.param序列化参数,jQuery.param( obj, traditional ),中traditional默认为false,即jquery会深度序列化参数对象,以适应如PHP框架, 但servelt api无法处理,可以通过设置traditional 为true阻止深度序列化,然后序列化结果如下:

ids: ["1", "2"] => ids = 1 & id s= 2
3. 解决
方案一

ajax 中添加 traditional: true 字段

$.ajax({
     url: "xxx",
     data: {'ids': ids},
     traditional: true,
     success: function (data) {
     ……
  }
});

方案二

对传输的数组进行处理

$.post('xxx', {auditNodes}, function (res) {
    if (res.code > 0) {
    } else {
        layer.msg(res.msg, {icon: 6, time: 1000}, function () {
        })
    }
}, 'json');

用一个中括号把所传数组处理一下