1

I'm trying to make a post call using resources from angular.js and adding a success and error callback.

wbsModule.factory('gridData', function($resource) {
    //define resource class
    var root = {{ root.pk }};
    var csrf = '{{ csrf_token }}';
    return $resource('{% url getJSON4SlickGrid root.pk %}:wpID', {wpID:'@id'},{
            get: {method:'GET', params:{root : root }, isArray:true},
            update:{method:'POST', headers: {'X-CSRFToken' : csrf }},
      });
});

I'm calling the update action like this:

args.item.$update([], successUpdateCallback, errorUpdateCallback);

where I followed this part of the docs:

non-GET instance actions: instance.$action([parameters], [success], [error])

The server returns json like this if an error occurs:

jsonReturn = [{'error' : "Oops.. a problem occured. We could not save your last change in the highlighted row: "}]
        jsonReturn.append({'wp_id' : wp_id})
        try:
            for key, value in wpForm.errors.iteritems():
                jsonReturn.append({"form_errors" : "<br/>" + str(value)})
        except Exception, e:
            print e
        return HttpResponse(json.dumps(jsonReturn, indent=4), mimetype="application/json", status=400)

For the error callback I am able access the error messages like this:

     function errorUpdateCallback(result){
            console.log(result.data);
            error = result.data[0].error;
            wp_id = result.data[1].wp_id;
            form_errors = result.data[2].form_errors;
            }
        };

But when I try to do the same for the success function I'm getting this error, which is thrown before entering the successUpdateCallback:

'undefined' is not a function (evaluation 'a.push(U(b[c]))')
 http://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js

Where I create the json the same as in the error case at the server:

jsonReturn = [{'message' : "Successfull update."}]
return HttpResponse(json.dumps(jsonReturn, indent=4), mimetype="application/json", status=200)

and parsing the success callback the same as the error callback:

        function successUpdateCallback(result){
            console.log("in suc. update");
            console.log(result);
            message = result.data[0].message;
        };

Whereas when I return an empty json object I do not get this error and the successUpdateCallback is entered, printing "in suc.update" to the console:

jsonReturn = []
return HttpResponse(json.dumps(jsonReturn, indent=4), mimetype="application/json", status=200)
4

1 回答 1

2

备查:

Angular 期望服务器以我们调用 $update 或 $save 的资源的 json 表示来响应成功的 post 调用。

我在这里找到了。隐藏在评论中:)

 card.$save();
 // POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'}
 // server returns: {id:456, number:'1234', name: 'J. Smith'};

因此,我从服务器返回资源的 json 表示形式,它按预期工作。

于 2012-11-14T14:24:40.117 回答