繁体   English   中英

AngularJS - $ http.post以json的形式发送数据

[英]AngularJS - $http.post send data as json

我正在使用angularjs处理自动完成指令但有一些问题。

我有一个具有自动完成输入的表单。 当我在那里输入内容时, 术语变量将作为JSON发送:

在此输入图像描述

但是,当我使用相同的功能(来自不同的角度控制器,但相同的功能)在另一种形式时, 术语变量发送完美,自动完成工作正常:

在此输入图像描述

这是我的角度函数:

$scope.getCustomers = function (searchString) {
    return $http.post("/customer/data/autocomplete",
        {term: searchString})
        .then(function (response) {
            return response;
        });
};

你觉得怎么了?

使用JSON.stringify()来包装你的json

var parameter = JSON.stringify({type:"user", username:user_email, password:user_password});
    $http.post(url, parameter).
    success(function(data, status, headers, config) {
        // this callback will be called asynchronously
        // when the response is available
        console.log(data);
      }).
      error(function(data, status, headers, config) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
      });

考虑在$ http.post中显式设置标题(我把应用程序/ json,因为我不确定您的示例中的哪两个版本是工作的,但您可以使用application / x-www-form-urlencoded if它是另一个):

$http.post("/customer/data/autocomplete", {term: searchString}, {headers: {'Content-Type': 'application/json'} })
        .then(function (response) {
            return response;
        });

我认为最合适的方法是在使用你的“get”请求时使用相同的代码角度使用$httpParamSerializer必须将它注入你的控制器,所以你可以简单地执行以下操作而不必使用Jquery, $http.post(url,$httpParamSerializer({param:val}))

app.controller('ctrl',function($scope,$http,$httpParamSerializer){
  $http.post(url,$httpParamSerializer({param:val,secondParam:secondVal}));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM