【问题标题】:Save data over json通过 json 保存数据
【发布时间】:2014-02-13 22:40:56
【问题描述】:

我使用grails 2.3.4 作为我的angularjs 1.2.8 应用程序的后端。

我想将我的数据保存到数据库中。我试图这样实现它:

testApp.controller('testController', function($scope, $rootScope, $http, $location) {
$scope.product = {};

$scope.saveProduct = function() {
    console.log('call saveProduct');
    $http
     .post($rootScope.appUrl + '/product.json', $scope.book)
     .success(function(data, status, headers, config) {
  $location.path('/product');
     }).error(function(data, status, headers, config) {
    });
}

});

原则上这应该可行,因为我的后端使用@Resource(uri='/product') 来提供 RESTFUL API。我可以这样称呼所有现有产品:http://localhost:8080/testApplication/product.json

但是 chrome 控制台诊断给了我:

POST http://localhost:8080/testApplication/undefined/product.json 404 (Not Found)

undefined 使此链接失效。有什么建议可以去掉吗?

关于如何更改我的功能以使其正常工作的任何建议?

【问题讨论】:

    标签: javascript json angularjs grails grails-2.0


    【解决方案1】:

    当您调用 $http.post() 时,$rootScope.appUrl 看起来像 undefined。尝试将$rootScope.appUrl 的值记录到控制台以确保。如果是undefined,请将其设置为您需要的任何内容,以匹配您的后端期望的 URL。


    编辑:我不熟悉 Angular 的细节或传递给此方法的具体内容,但您可以通过检查变量是否已定义来更加健壮,如下所示:

    $scope.saveProduct = function() {
      var url = 'products.json';
    
      if($rootScope && $rootScope.appUrl) {
        url = $rootScope.appUrl + '/' + url;
      }
    
      console.log('call saveProduct');
      $http
      .post(url, $scope.book)
      .success(function(data, status, headers, config) {
        $location.path('/product');
      })
      .error(function(data, status, headers, config) {});
    }
    

    【讨论】:

    • 感谢您的回答!问题是唯一让我与储蓄区分开来的词是undefined。这个 url 可以保存我的数据:http://localhost:8080/testApplication/product.json 有什么建议可以杀死 javascript 中的 undefined 吗?
    • 感谢您的回答!我的问题是我仍然得到这样的链接:http://localhost:8080/product
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-03
    • 1970-01-01
    • 1970-01-01
    • 2014-02-01
    • 1970-01-01
    相关资源
    最近更新 更多