【问题标题】:AngularJS post method is not workingAngularJS发布方法不起作用
【发布时间】:2016-06-01 16:08:36
【问题描述】:

我正在尝试将一些数据与帖子一起发送到特定的 url,该 url 后面有一个 php 脚本。目前我无权访问 php 脚本。 php 脚本检查字符串是否与数据库中的任何记录匹配,如果匹配则返回该记录。如果没有匹配,脚本将返回所有记录。

以下代码是我目前所拥有的。如您所见,我有一个字符串 命名:不应该找到任何结果字符串。这实际上不应该返回任何结果。但是,它返回所有记录而不是没有记录。

我尝试了什么:

  • 使用params 而不是data
  • 使用不同的Content-types
  • 使用 post 方法的简短版本

$http({
    url: $scope.url,
    method: "POST",
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    data: {search: "shouldnotfindanyresultsstring"}
}).then(function (response) {
    console.log(response);
}, function (response) { // optional
    console.log("Still not working");
});

所以最终我想用搜索字符串搜索数据库中的记录。但是我没有让它工作。

使用邮递员,我可以生成有效的帖子。我确实有一种强烈的感觉,它与Content-type有关

【问题讨论】:

  • 你能把Postman做的HTTP请求贴出来吗?
  • 从服务器获取数据而不更改任何数据应该是 GET 方法。这与您的问题无关,但我认为如果您不知道,您应该知道这一点。
  • @str 不确定这是不是你的意思,但我添加了一个 key: 搜索和一个 value: stringwithnoresults。在邮递员中,这给了我结果null。在应用程序中,这会将所有记录返回给我
  • @Thijs 是的,我知道这一点,但我需要用字符串搜索一些记录
  • @RSSD 这是模棱两可的。请在 Postman 中为您的请求单击“生成代码”并发布 HTTP 请求。

标签: javascript angularjs postman


【解决方案1】:

如果您想使用 'application/x-www-form-urlencoded' 则将数据格式化为字符串

data: "search=shouldnotfindanyresultsstring"

如果你想使用 'application/json' 然后使用这个:

var jsonData = { search : "shouldnotfindanyresultsstring" };

$http({
    method: 'POST',
    url: $scope.url,
    contentType: 'application/json',
    data: JSON.stringify(jsonData),
}).
    success(function (data) {
        console.log(data);
    }).
    error(function (message, status) {
        console.log(message);
    });

【讨论】:

  • 谢谢,这个确实有效!我用data : "search=shouldnotfindanyresultsstring"
  • 太棒了!祝你有美好的一天
【解决方案2】:

如果您想使用x-www-form-urlencoded,您需要将数据实际编码为字符串。 Angular 总是将你的对象作为 JSON 编码的对象发布到你的正文中,即使你指定了该标头。

this answer中有解释并提供解决方案

【讨论】:

    【解决方案3】:

    试试这个:

    $http.post($scope.url, JSON.stringify("shouldnotfindanyresultsstring"), { headers: {'Content-Type': 'application/x-www-form-urlencoded'} })
    

    或者这个:

     $http.post($scope.url, JSON.stringify({search: "shouldnotfindanyresultsstring"}), { headers: {'Content-Type': 'application/x-www-form-urlencoded'} })
    

    【讨论】:

      猜你喜欢
      • 2013-03-23
      • 1970-01-01
      • 2015-08-21
      • 2017-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多