我想将所有复选框ID和已检查的参数(1或0)作为json列表发送到server.I尝试和googled多次但无法得到任何结果。我得到语法上错误的错误
我的java代码:
@Autowired
ParamService paramService;
@RequestMapping(value = "/refresh", method = RequestMethod.POST, produces = "application/json", consumes = "application/json")
public @ResponseBody String refreshModelParamRel(@RequestBody ParamWrapper pw) {
System.out.println("params size"+pw.getParams().size());
}
ParamWrapper:
public class ParamWrapper {
private List<ParamDTO> params;
private Integer modelId;
public ParamWrapper() {
}
public List<ParamDTO> getParams() {
return params;
}
public void setParams(List<ParamDTO> params) {
this.params = params;
}
public Integer getModelId() {
return modelId;
}
public void setModelId(Integer modelId) {
this.modelId = modelId;
}
}
和我的json:
function addModelParams() {
var paramWrapper = {};
paramWrapper["modelId"] = selectedModelId;
var params = {};
var allParams = $("input[name='param']");
for (i = 0; i < allParams.length; i++) {
var param = {};
param["id"] = allParams[i].value;
param["checked"] = allParams[i].checked;
params[i] = param;
}
paramWrapper["params"] = params;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function ()
{
if (xhr.readyState == 4 && xhr.status == 200)
{
alert(xhr.responseText);
}
}
xhr.open("POST", "http://localhost:8080/ButelefonAPI/modelparams/refresh", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(paramWrapper));
}
在我发送的json数据中似乎一切正常:
{"modelId":13,"params":{"0":{"id":"1","checked":false},"1":{"id":"2","checked":false},"2":{"id":"3","checked":false},"3":{"id":"4","checked":false},"4":{"id":"5","checked":false},"5":{"id":"6","checked":false},"6":{"id":"7","checked":false},"7":{"id":"9","checked":false},"8":{"id":"10","checked":false},"9":{"id":"11","checked":false},"10":{"id":"12","checked":false},"11":{"id":"13","checked":false},"12":{"id":"14","checked":false},"13":{"id":"15","checked":false},"14":{"id":"16","checked":false},"15":{"id":"17","checked":false},"16":{"id":"21","checked":false}}}
答案 0 :(得分:0)
修改强>
好的,我认为语法问题在于您的params = {}
对象应该是一个数组params = []
而是
更改:
var paramWrapper = {};
var params = {};
var allParams = $("input[name='param']");
for (i = 0; i < allParams.length; i++) {
var param = {};
param["id"] = allParams[i].value;
param["checked"] = allParams[i].checked;
params[i] = param;
}
paramWrapper["params"] = params;
对此:
var paramWrapper = {};
var params = [];
var allParams = $("input[name='param']");
for (i = 0; i < allParams.length; i++) {
var param = {};
param["id"] = allParams[i].value;
param["checked"] = allParams[i].checked;
params[i] = param;//or params.push(param);
}
paramWrapper["params"] = params;
我认为应该这样做。