使用骨干中的json文件模拟集合不会触发主干中的成功回调

时间:2014-05-06 06:55:29

标签: javascript jquery json backbone.js

我正在尝试使用.json文件来模拟骨干集合中的GET请求。这是我的示例文件:

[
    {
        "id": '11111',
        "name": "Abdominal Discomfort",
        "favorite": true
    },
    {
        "id": "11110",
        "name": "Abdominal Distension",
        "favorite": true
    },
    {
        "id": "11101",
        "name": "Swollen Abdomen",
        "favorite": true
    },
    {
        "id": "11011",
        "name": "Disorder of Fetal Abdominal Region",
        "favorite": false
    },
    {
        "id": "11100",
        "name": "Dissect of Abdominal Aorta",
        "favorite": false
    },
    {
        "id": "11000",
        "name": "Umbilical Discharge",
        "favorite": false
    }
]

这是我的骨干模型/收集实体:

define(['Backbone'], function (Backbone) {
    "use strict";
//MODEL
    var diagnosis = Backbone.Model.extend({});

//COLLECTION
    var c = Backbone.Collection.extend({
        model: diagnosis,
        url:'app-src/js/data-mocks/diagnosis.json'
    });


    return {
        model: diagnosis,
        collection: c
    };

});

最后我在我的视图中进行了这样的提取调用:

var that=this;
this.collection.fetch({wait:true,success:function(){
    console.log(that.collection);
}});

在网络控制台中,我看到正确的200状态响应,其中返回了一组对象。但是,成功回调永远不会被触发。此外,我确信.on'添加'绑定的事件和永远不会调用它们的回调。

请建议我出错的地方。

1 个答案:

答案 0 :(得分:0)

这发生在我身上几次,所以我决定制作一个迷你PHP API接口来设置正确的Header内容类型,然后提供JSON文件。我认为它正在获取JSON,而jQuery正试图将其解析为XML。这意味着您可能需要强制“json”的请求标头。试试这个:

var that=this;
this.collection.fetch({wait:true, dataType: 'json', success:function(){
    console.log(that.collection);
}});