AJAX 向后台发送带 List 集合的对象


现有基类:

public class School {
    int name;
    int address;
    List<Student> students = new ArrayList<Student>();
}

public class Student {
    int name;
    int sex;
}

现在我需要通过ajax向后台传输一个包含所有学生集合的School对象:

传输的数据格式为:

school: {
    "name" : "清华大学",
    "address" : "北京",
    "students" : [{
        "name" : "张三",
        "sex" : "20"
    },{
        "name" : "李四",
        "sex" : "20"
    }]    
}

js 中的实现:

var school = {};
school.name = '清华大学';
school.address = "北京";
//此处使用的是 easyui 插件来获取数据
var rows = $('#maintainTableId').datagrid('getSelections');
for (var i = 0; i < rows.length; i++) {
    school["students [" + i + "].name"] = rows[i].name;
    school["students [" + i + "].sex"] = rows[i].sex;
}

$.ajax({
    url : url,
    type : 'POST',
    dataType : 'json',
    data : school,
    success : function() {}
})

注意:

    ajax 的请求参数  contentType 可能会影响到服务器端接受参数, 如果JS端发送的JSON数据(此处的数据指的是利用字符

 串拼接为JSON格式的参数并不是本例中的JSON对象格式)为简单常见的JSON格式则不会受影响,但是当JS发送到服务

   器端的JSON数据比较复杂时(例如本例中的JSON包含数组),默认的contentType(application/x-www-form-urlencoded)

   不能识别,需要更改为 'application/json' 才能识别。

    contentType的设置参考: https://blog.csdn.net/m0_37572458/article/details/78622668?locationNum=6&fps=1

    


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM