在我的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字段中的数据。任何帮助表示赞赏。
最佳答案
您需要等待查询已完成获取
function () {
var self = this;
this.fetch({
success: function(response) {
// store your response from here
self.sizes = response;
}
});
}