尝试在变量中存储responseJSON会导致“未定义”错误

时间:2015-07-06 14:17:25

标签: javascript json rest backbone.js

在我的REST应用程序中,我尝试使用http GET方法获取数据。作为响应,我得到一个带有responseText和responseJSON字段的对象,如下所示:

Object {readyState: 1}
abort: ( statusText ) {
always: () {
complete: () {
done: () {
error: () {
fail: () {
getAllResponseHeaders: () {
getResponseHeader: ( key ) {
overrideMimeType: ( type ) {
pipe: ( /* fnDone, fnFail, fnProgress */ ) {
progress: () {
promise: ( obj ) {
readyState: 4
responseJSON: Array[3]
responseText: "[{"id":1,"name":"Standard"},{"id":2,"name":"Small (32 cm)"},{"id":3,"name":"Big (42 cm)"}]"
setRequestHeader: ( name, value ) {
state: () {
status: 200
statusCode: ( map ) {
statusText: "OK"success: () {then: ( /* fnDone, fnFail, fnProgress */ ) {
__proto__: Object 

当我尝试在变量中存储responseText或responseJSON时,它会在控制台中导致“未定义”错误。这是代码的一个片段:

define([
    'backbone'
],
    function (Backbone) {
        'use strict';

        return Backbone.Collection.extend({
            initialize: function () {
                this.sizes = this.fetch();
            },

            url: 'http://localhost:8080/sizes',

            getContext: function () {
                var sizelist = this.sizes.responseJSON;
                return sizelist;
            }
        });
    });

当我尝试执行console.log()时,变量“sizelist”是未定义的,尽管“this.sizes”是上面提到的对象。问题是如何获取存储在responseJSON或responseText字段中的数据。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

您需要等待查询完成才能获取

       function () {
            var self = this;
            this.fetch({
                success: function(response) {
                    // store your response from here
                    self.sizes = response;
                }
            });
        }