【问题标题】:POST works using JQuery but not AngularjsPOST 使用 JQuery 而不是 Angularjs
【发布时间】:2015-08-16 03:54:29
【问题描述】:

谁能帮我找出为什么这段代码可以正常工作:

       $.ajax({
                type: "POST",
                url: scope.serviceBase + "/api/Property/PostAsync",
                contentType: "application/x-www-form-urlencoded",
                processData: false,
                data: data,
                success: function (response) {
                    alert(response);
                },
                error: function (response) {
                    alert(response);
                }
            });

虽然完全相同的事情只是使用 Angularjs 失败了:

      $http({
                method: "POST",
                url: scope.serviceBase + 'api/Property/PostAsync',
                headers: {
                    'processData':false,
                    'Content-Type': "application/x-www-form-urlencoded"
                },
                data: data
            }).success(function (response) {
                alert(response);
            }).error(function (response) {
                alert(response);
            });

仅供参考,我使用 AngularJs 格式时遇到的错误是 400 bad request。

【问题讨论】:

  • 我认为 AngularJS 中不存在 ProcessData。如果 processData 的目的是将数据转换为 post 或 get,则称为 transfromRequest 和 transformResponse。这些不在标题内

标签: jquery angularjs post http-post bad-request


【解决方案1】:

首先,processData 不是标题,它在 Angular 中(目前)不存在,因为它存在于 jQuery 中。不过,它有一个transformRequest 属性用于$http,它接受一组函数,这些函数将在发送请求之前在数据属性上执行。为了告诉 Angular 不要碰你的数据,你可以简单地将该配置设置为一个空数组。所以在你的情况下应该是这样的

$http({
           method: "POST",
           url: scope.serviceBase + 'api/Property/PostAsync',
           headers: {
                       'Content-Type': "application/x-www-form-urlencoded"
                    },
           data: data,
           transformRequest: []
           }).success(function (response) {
               alert(response);
           }).error(function (response) {
               alert(response);
           });

【讨论】:

    【解决方案2】:

    试试:

    $http.post(scope.serviceBase + 'api/Property/PostAsync', data).success(function(response) {
        alert(response);
    })
    .error(function(response) {
        alert(response);
    })
    

    在我看来,我认为 post 请求在语法上与 jQuery 有点不同。上面的代码是我在 Angular 中使用的。更多配置选项请参考this

    【讨论】:

    • 请编辑更多信息。不鼓励使用纯代码和“试试这个”的答案,因为它们不包含可搜索的内容,也没有解释为什么有人应该“试试这个”。我们在这里努力成为知识的资源。
    猜你喜欢
    • 2015-06-02
    • 1970-01-01
    • 2014-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-04
    • 2010-09-07
    相关资源
    最近更新 更多