简体   繁体   English

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

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

I'm working on autocomplete directive with angularjs but having some issues. 我正在使用angularjs处理自动完成指令但有一些问题。

I have a form which have an autocomplete input. 我有一个具有自动完成输入的表单。 When i type something there, the term variable is sent as JSON: 当我在那里输入内容时, 术语变量将作为JSON发送:

在此输入图像描述

But, when i use the same function (from different angular controller, but the same function) in another form the term variable sent perfectly and the autocomplete works fine: 但是,当我使用相同的功能(来自不同的角度控制器,但相同的功能)在另一种形式时, 术语变量发送完美,自动完成工作正常:

在此输入图像描述

Here is my angular function: 这是我的角度函数:

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

What do you think is wrong? 你觉得怎么了?

Use JSON.stringify() to wrap your json 使用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.
      });

Consider explicitly setting the header in the $http.post (I put application/json, as I am not sure which of the two versions in your example is the working one, but you can use application/x-www-form-urlencoded if it's the other one): 考虑在$ 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;
        });

i think the most proper way is to use the same piece of code angular use when doing a "get" request using you $httpParamSerializer will have to inject it to your controller so you can simply do the following without having to use Jquery at all , $http.post(url,$httpParamSerializer({param:val})) 我认为最合适的方法是在使用你的“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