用ajax向后台传递数组乱码解决方法

xiaoxiao2021-02-28  84

var result = ['1','2','3'];

$.ajax({ type: "GET", url:"http://xxxxxxxx", data:{              groups:result,  }, dataType:'json',  success: function (Json) {        console.log("success");  },  error:function(){       console.log("error");  }

})       

传递的数组groups后面出现了乱码。

原因是:当传递数组时,会在我们的数组名称后自动加上”[]”,在java后台是无法取到参数的,因为jQuery需要调用jQuery.param序列化参数,jQuery.param( obj, traditional )默认的话,traditional为false,即jquery会深度序列化参数对象,以适应如PHP和Ruby on Rails框架,但servelt api无法处理,我们可以通过设置traditional 为true阻止深度序列化,然后序列化结果如下:

groups: ["1", "2", "3"]    =>    groups=1&groups=2&groups=3

最好在上述ajax代码中添加:

traditional: true,

传递正确。

转载请注明原文地址: https://www.6miu.com/read-72857.html

最新回复(0)