javascript - 在 spring Controller 中使用 angularJs $http 将对象作为 json 键发送返回 null

标签 javascript angularjs json spring

我正在尝试将 json objectjavascript 发送到 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/

相关文章:

javascript - 通过 AJAX 和 Controller 在 Rails 中渲染 View

Javascript按时间倒序对对象数组进行排序

javascript - 在 angularjs 中构建 promise

ios - 如何从json获取值并将其存储为变量

Java json 将值附加到 json 数组

python - 在 Python 中将自定义对象序列化为 JSON 的方法

java - 通过 JQuery 返回的渲染列表

javascript - 将此变量传递给 Angular $http 回调

javascript - 如何使用 AngularJS foreach 使用 json 中的键获取特定值

javascript - 构建并运行后,是否可以在浏览器中查看以 Angular 声明的 secret 变量?