【问题标题】:AngularJS - $http.post send data as jsonAngularJS - $http.post 以 json 格式发送数据
【发布时间】:2023-03-31 22:05:01
【问题描述】:

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

我有一个具有自动完成输入的表单。当我在那里输入内容时,term 变量 以 JSON 格式发送:

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

这是我的角度函数:

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

你觉得哪里不对?

【问题讨论】:

  • 我在文档中注意到的唯一相关的事情是“如果请求配置对象的数据属性包含一个对象,请将其序列化为 JSON 格式。”但是如果在你调用 getCustomers 的两个地方你只传递一个字符串,那么我不知道为什么它会有所不同。
  • 不知道为什么会这样。你能在这里试试建议的答案吗:stackoverflow.com/questions/17547227/…
  • 您需要提供表单的 HTML 和实际调用此方法的 JavaScript。否则,任何人说的任何话都只是猜测。我敢打赌你在别处有一个错误。

标签: json angularjs http post


【解决方案1】:

考虑在 $http.post 中显式设置标头(我放置了 application/json,因为我不确定您示例中的两个版本中的哪一个是有效的,但您可以使用 application/x-www-form -urlencoded 如果是另一个):

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

【讨论】:

    【解决方案2】:

    使用 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.
          });
    

    【讨论】:

    • 如果我在服务器代码中引用此参数,它只是在请求正文中发送,还是有某种方法可以给参数一个键,以便我可以通过引用键来获取它在我的服务器上?
    【解决方案3】:

    我认为最合适的方法是在使用您$httpParamSerializer 进行“获取”请求时使用相同的代码角度使用将不得不将其注入您的控制器,这样您就可以简单地执行以下操作而不必使用完全是 Jquery,$http.post(url,$httpParamSerializer({param:val}))

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-15
      • 1970-01-01
      • 2012-08-24
      • 2017-04-30
      • 1970-01-01
      • 1970-01-01
      • 2016-04-27
      • 2017-02-06
      相关资源
      最近更新 更多