AngularJS post方法不起作用



我正在尝试将一些数据与帖子一起发送到一个特定的网址,该网址后面有一个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

有关

如果你想使用'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);
    });
如果要

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

本答案对此进行了解释并提供解决方案

试试这个:

$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'} })