AngularJS post方法无效

时间:2016-06-01 07:29:28

标签: javascript angularjs postman

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

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

我尝试了什么:

  • 使用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

有关

3 个答案:

答案 0 :(得分:0)

试试这个:

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

答案 1 :(得分:0)

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

this answer中对此进行了解释并提供了解决方案

答案 2 :(得分:0)

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