jquery - Angular `$.ajax` 可以工作,但 '$resource` - 抛出错误如何解决这个问题?

标签 jquery angularjs ajax

在我的应用程序中,我尝试向服务器POST请求。为此,我使用 $resource 模块。但是,当我尝试发布该对象时,我收到错误 TypeError: server.batchUpdate.save(...).$promise is not a function 并且我无法发布在所有..

这是代码:

$scope.batchUpdate = function ( object ) {

        var newId = Number(object.Id);
        var newType = 'project';
        var newImportant = !object.IsImportant;

        var newobject = {

            "Id" : newId,
            "Type" : newType,
            "IsImportant"  : newImportant

        }

        console.log( newImportant, newId ); //updates

        server.batchUpdate.save({

            "updateImportant" :  JSON.stringify(newobject)

        })
        .$promise().then(function ( response ) {

            cosole.log( response );

        });

    }

我尝试过,但根本无法解决问题。后来我尝试使用直接 jQuery ajax 方法,效果很好。 这是代码:

$scope.batchUpdate = function ( object ) {

        var newId = Number(object.Id);
        var newType = 'project';
        var newImportant = !object.IsImportant;

        var newobject = {

            "Id" : newId,
            "Type" : newType,
            "IsImportant"  : newImportant

        }

        var param = { "updateImportant":newobject };

        $.ajax({
           type: "POST",
           url: "http://azvsptcsdev02:678/_vti_bin/CPMD.WEBSERVICE/ProjectInfoService.svc/UpdateImportantbyUser",
           data: JSON.stringify(param),
           contentType: "application/json; charset=utf-8",
           dataType: "json",
           processData: true,
           success: function (data, status, jqXHR) {
               console.log("success" + data, status, jqXHR ); /*getting response*/
           },
           error: function (xhr) {
               console.log('failure', xhr.responseText);
           }
       });


    }

但我更喜欢使用$resource方式。我需要对我的 $resource 帖子做什么?有人可以帮帮我吗?

最佳答案

问题是您尝试将 .$promise 用作函数而不是属性。您应该如下所示,请注意 .$promise 未被调用,而是被访问(不带括号)。

$scope.batchUpdate = function (obj) {
    var newId = Number(obj.Id);
    var newType = 'project';
    var newImportant = !object.IsImportant;

    var newobject = {
        "Id" : newId,
        "Type" : newType,
        "IsImportant"  : newImportant
    };

    console.log(newImportant, newId); // Updates

    server.batchUpdate.save({
        "updateImportant" :  JSON.stringify(newobject)
    })
    .$promise.then(function(response) {
        cosole.log(response);
    });
}

关于jquery - Angular `$.ajax` 可以工作,但 '$resource` - 抛出错误如何解决这个问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34336780/

相关文章:

javascript - 在 jquery 中动态传递事件数据

java - Spring Boot 和 Jquery 从前端的 hashmap 访问值

javascript - 将多组单选按钮值存储到对象 angularjs 中(不使用 jQuery)

javascript - 在ajax错误上执行javascript函数

php - 在 AJAX 中使用 PHP 对象值

javascript - 用于 firebase 的 Cloud Functions 返回响应 500

javascript - 使用下拉列表的新值在下拉列表更改时重新加载数据表

javascript - 为什么我的 jquery 没有改变我的 div ?

json - 使用 AngularJS 从 json 检索数据

javascript - 当模型数据在 angularjs 中的表单之外更改时,如何正确检查观察者中的表单有效性?