【问题标题】:How to access json return values in angular.js action success callback如何在 angular.js 动作成功回调中访问 json 返回值
【发布时间】:2012-11-01 18:36:11
【问题描述】:

我正在尝试使用来自 angular.js 的资源进行发布调用并添加成功和错误回调。

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 }},
      });
});

我这样调用更新操作:

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

我在哪里关注了 part 的文档:

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

如果发生错误,服务器会返回这样的json:

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)

对于错误回调,我可以访问如下错误消息:

     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;
            }
        };

但是当我尝试对成功函数执行相同操作时,我收到了这个错误,该错误是在输入 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

我创建 json 的位置与服务器上的错误情况相同:

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

并且解析成功回调和错误回调一样:

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

而当我返回一个空的 json 对象时,我没有收到此错误,并且输入了 successUpdateCallback,将“in suc.update”打印到控制台:

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

【问题讨论】:

    标签: django json resources angularjs


    【解决方案1】:

    供将来参考:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-07
      • 1970-01-01
      • 2011-04-30
      • 2014-06-29
      • 1970-01-01
      相关资源
      最近更新 更多