【问题标题】:How to read json data from AngularJs (front end) to Grails (server side) through $http如何通过 $http 从 AngularJs(前端)读取 json 数据到 Grails(服务器端)
【发布时间】:2015-09-13 05:41:21
【问题描述】:

我必须通过 $http 服务方法从 Angular 向 Grails 发送 json 数据。 JSON 数据已发送到服务器。但在服务器端它不打印参数值。我是 Grails 的新手。

我的代码:

控制器:

$(function(){

    gateApp.factory('saveCreateToServer', function($http){
        return {
            saveDataToServer:function(taskCreateFormData){
                console.log(taskCreateFormData);

                return $http({
                    method  : 'POST',
                    url     : 'save',
                    data    :  taskCreateFormData, 
                })
            }
         }
    });

    gateApp.controller('moveTaskRuleDefCtrl', function($scope, saveCreateToServer){
        $scope.saveCreate=function() {
            var reqData = angular.toJson($scope.taskCreateForm);
            saveCreateToServer.saveDataToServer(reqData).success(function(data) {
            });
        }
    });
})

在服务器端:

 def save(params){
        println "<<<<<<<<<uu<<<<<<<<<"+params
}

【问题讨论】:

    标签: javascript json angularjs grails


    【解决方案1】:

    当您使用$httpdata 键发布数据时,数据不会作为查询或表单数据发送,而是使用正文参数发送。所以你不能用params读,直接用request.JSON

    def save() {
        Map requestData = request.JSON
        println "Data: " + requestData
        println "Data: " + requestData.firstName
    }
    

    另外,您不必将对象转换为 JSON 字符串,只需传递数据即可:

    $http({
        method: "POST",
        url: "/save",
        data: {firstName: "John", lastName: "Doe"}
    });
    

    将数据作为表单数据传递的更新

    是的,您绝对可以这样做,这样您就不必更改服务器端代码。所以基本上,Angular 默认将Content-Type 的数据发送为application/json,因此Grails 将其接收为request.JSON。所以只要把它改成application/x-www-form-urlencoded

    $http({
        method: "POST",
        url: "/save",
        data: {firstName: "John", lastName: "Doe"},
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    });
    

    现在,参数将在 Grails 控制器中以 params 的形式提供。

    【讨论】:

    • 很好。实际上我正在迁移到 Angular js..所以现在我无法更改服务器端代码..所以我怎样才能更改和发送 json 数据有利于 params 接收方法..我想通过使用 params 接收 json 数据..那我该怎么办..
    • 当然,我已经更新了答案,包括解决您的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-09
    • 2018-03-27
    • 1970-01-01
    相关资源
    最近更新 更多