【问题标题】:Sending data from form to POST request in Angular在Angular中将数据从表单发送到POST请求
【发布时间】:2015-09-26 06:42:17
【问题描述】:

我想使用 Angular 发出 POST 请求。我正在使用 ng-submit 将表单提交给我访问工厂的控制器以使用以下方式发出请求:

$http.post('/droplets', data)

我需要将表单字段中的数据放入上面的“数据”变量以发送到我的 API,但是当它有多个字段时,我不知道如何执行此操作。这是怎么做到的?

【问题讨论】:

  • 你为什么不直接给出action="/droplets" method="post" 并让它自己提交呢? ng-submit 仍然会被触发
  • 我不想刷新页面。我想使用 AJAX。

标签: angularjs forms post


【解决方案1】:

试试这个...

$http({
        url: '/droplets',
        method: "POST",
        data: JSON.stringify({application:app, from:data1, to:data2}),
        headers: {'Content-Type': 'application/json'}
      }).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.
        });
};

参考:https://docs.angularjs.org/api/ng/service/$http

【讨论】:

  • 谢谢。你能解释一下:data: JSON.stringify({application:app, from:data1, to:data2}) 吗?我不确定括号里应该写什么。
  • 请求类似于 "{"application":"appname","from":"test","to":"test"}"
  • 我还是不清楚。 “from:”和“to:”指的是什么?
  • from和to是test和test的key,见上面的json
猜你喜欢
  • 2019-02-25
  • 1970-01-01
  • 2020-06-05
  • 2017-04-23
  • 2021-05-07
  • 2022-11-19
  • 2013-07-07
  • 2019-09-15
相关资源
最近更新 更多