如何访问angular.js行动成功回调JSON返回值回调、返回值、行动、angular

由网友(▲▲美国范i)分享简介:我试图使利用angular.js资源,增加了成功和错误回调后调用。 wbsModule.factory('的GridData',函数($资源){    //定义资源类    VAR根= {{root.pk}};    VAR CSRF ='{{csrf_token}}';    返回$资源('{%URL getJS...

我试图使利用angular.js资源,增加了成功和错误回调后调用。

  wbsModule.factory('的GridData',函数($资源){    //定义资源类    VAR根= {{root.pk}};    VAR CSRF ='{{csrf_token}}';    返回$资源('{%URL getJSON4SlickGrid root.pk%}:wpID',{wpID:@ ID},{            得到:{方法:GET,则params:{根:根},IsArray的:真正},            更新:{方法:POST,标题:{'X-CSRFToken':CSRF}},      });}); 

我打电话这样的更新操作:

  args.item $更新([],successUpdateCallback,errorUpdateCallback)。 

在这里我跟着这个部分文档的:

 非获得实例动作:例如$行动([参数],[成功],[错误]) 
AngularJS 为什么成功了

服务器返回JSON这样如果发生错误:

  jsonReturn = [{错误:哎呀呀..有问题发生,我们无法保存您的最后一次更改突出显示的行中:}]        jsonReturn.append({'wp_id':wp_id})        尝试:            关键在wpForm.errors.iteritems)值(:                jsonReturn.append({form_errors:< BR />中+ STR(值)})        除例外,E:            打印E        返回的Htt presponse(json.dumps(jsonReturn,缩进= 4),MIME类型=应用/ JSON,状态= 400) 

有关错误回调我能获得这样的错误信息:

 函数errorUpdateCallback(结果){            的console.log(result.data);            错误= result.data [0] .error;            wp_id = result.data [1] .wp_id;            form_errors = result.data [2] .form_errors;            }        }; 

但是,当我试图为成功的功能我得到这个错误,这是进入前successUpdateCallback抛出做相同的:

 未定义不是一个函数(评估'a.push(U(B [C]))') http://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js 

我在哪里创建JSON一样在服务器错误案例:

  jsonReturn = [{消息:全成更新​​}]返回的Htt presponse(json.dumps(jsonReturn,缩进= 4),MIME类型=应用/ JSON,状态= 200) 

和解析成功回调相同错误回调:

 函数successUpdateCallback(结果){            的console.log(在SUC更新。);            的console.log(结果);            消息= result.data [0] .message;        }; 

而当我返回一个空的JSON对象,我没有得到这个错误,并且successUpdateCallback输入,打印,在suc.update到控制台:

  jsonReturn = []返回的Htt presponse(json.dumps(jsonReturn,缩进= 4),MIME类型=应用/ JSON,状态= 200) 

解决方案

有关将来参考:

角期待一个成功的电话后,服务器与我们称之为$更新或$保存资源的JSON重新presentation响应。

我发现它这里。藏在一个评论:)

 卡$保存()。 // POST:/用户/ 123 /卡/ 456 {ID:456,号码:1234,名称:'J。史密斯} //服务器返回:{ID:456,号码:1234,名称:'J.史密斯'}; 

所以我返回从服务器资源的JSON重新presentation,它按预期工作。

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)

解决方案

For future reference:

Angular is expecting for a successful post call that the server responds with the json representation of the resource for which we called $update or $save.

I found it here. Hidden in a comment :)

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

Therefore I'm returning the json representation of the resource from the server and it works as expected.

阅读全文

相关推荐

最新文章