【问题标题】:Sending HTTP Post with multiple data through AngularJS通过 AngularJS 发送带有多个数据的 HTTP Post
【发布时间】:2014-03-23 13:29:57
【问题描述】:

我正在使用 AngularJS。我想通过 AngularJS 在 HTTP 帖子中发送多个数据。后端运行 Cakephp,我已经验证了 Rest API 通过 python HTTP-post 工作。

我有一个看起来像这样的控制器;

angular.module('myApp.controllers', []).
    controller('AlertDemoCtrl', ['$http', function($http) 
    {
        var post_url;
        var post_data;

        post_url="http://127.0.0.1/api_XXX/";

        post_data = {'data[Table1][field1]':'XX',
                     'data[Table2][0][field1]':'AA', 
                     'data[Table2][0][field2]':'BB', 
                     'data[Table2][0][field3]':'CC'
                    };

        $http.post(post_url, post_data);    
    }])

当我运行代码时,页面无法正确加载 AngularJS。如果我注释掉$http.post(post_url, post_data);,代码运行正常。我哪里做错了?

非常感谢。

【问题讨论】:

  • 您的错误信息是什么?由于您要发送一个数据对象(无论它由什么组成),肯定还有另一个问题。您的服务器是否可以通过此 URL 访问?
  • 是的。服务器可达。我使用 python 做了一个类似的 HTTP Post,它可以工作。我看不到错误消息。我只能看到页面没有正确显示。
  • 如何查看错误信息?来自 HTTP Post 响应?如何让 AngularJS 显示 HTTP Post 响应?
  • 使用浏览器的调试工具并查看控制台是否有错误消息或观察网络流量以查看发布响应。

标签: javascript angularjs http-post angularjs-http


【解决方案1】:

这里有两件事:

首先,对$http 请求的响应是通过 AngularJS 中的 Promises 处理的。如果您打算对服务器返回的响应做一些事情,您应该尝试将 Promise 处理添加到您的代码中。来自AngularJS官方docs(v1.3.0)

// Simple POST request example (passing data) :
$http.post(post_url, post_data).
  success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
  }).
  error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

其次,您可以尝试将您的 $http 调用封装在一个函数中,然后在加载页面的整个 AngularJS 后在事件上调用该函数。

angular.module('myApp.controllers', []).
controller('AlertDemoCtrl', ['$http', function($http) 
{
    var post_url;
    var post_data;

    post_url="http://127.0.0.1/api_XXX/";

    post_data = {'data[Table1][field1]':'XX',
                 'data[Table2][0][field1]':'AA', 
                 'data[Table2][0][field2]':'BB', 
                 'data[Table2][0][field3]':'CC'
                };

    $scope.fetch = function() {
        $http.post(post_url, post_data).success(function() {
            // handle response here
        }).error(function() {
            // handle error here
        });    
    }
}])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-14
    • 1970-01-01
    • 1970-01-01
    • 2014-06-06
    • 1970-01-01
    • 2017-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多