我正在尝试将 json
object
从 javascript
发送到 Spring Controller
。我正在使用 angularJs $http post 来实现这一点。当我将 key
作为 obejct
发送时,我得到的 LastName 为 null
。但是,当我将字符串
作为硬编码值发送时,该值会显示在 Controller
中。这是 Controller
代码:
@RequestMapping(value="/edit", method= RequestMethod.POST)
@ResponseBody
public void editInformation(@RequestBody UserDetails userDetails){
LOGGER.debug("THE LASTNAME IS: "+userDetails.getLastName());
//codes.....
}
这是 angularJs 代码:
$fieldProperty =$(this).attr("name");
$inputValue =$(this).val();
$http.post("/app/edit", {$fieldProperty : $inputValue}).success(function(result){
alert("Success "+result)
}).error(function(data, status){
//$log.info("The error is: "+data+ " and the error status code is: "+status)
alert("failure"+" and the data is: "+data+ " and the stis "+status)
});
以 JSON 形式发送 {$fieldProperty : $inputValue}
将返回 userDetails.getLastName()
作为 null。但是,发送 {"lastName": $inputValue}
返回正确的值。我检查了 alert($fieldProperty)
并且它返回了 lastName
。
我正在使用 Google Gson
库。
我在这里缺少什么吗?我将不胜感激你的帮助。谢谢。
最佳答案
要设置$fieldProperty
,您必须首先定义对象。此声明 ({$fieldProperty : $inputValue})
将键 '$fieldProperty'
添加到 Json Obj。这就是为什么您在 Spring Controller 中的姓氏为 null 的原因。你可以用这种方式
$fieldProperty =$(this).attr("name");
$inputValue =$(this).val();
var params = {};
params[$fieldProperty] = $inputValue;
$http.post("/app/edit", params).success(function () {
// Success Callback
});
关于javascript - 在 spring Controller 中使用 angularJs $http 将对象作为 json 键发送返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39584447/