【问题标题】:Backbone.Collection.fetch() always returns 404 while using jQuery.Mockjax to mock the resulting JSONBackbone.Collection.fetch() 在使用 jQuery.Mockjax 模拟生成的 JSON 时总是返回 404
【发布时间】:2014-03-31 22:27:09
【问题描述】:

我有一个简单的设置,如下所示:

Main.js:

(function($) {
    "use strict";

    var Company = Backbone.Model.extend({
        defaults: {
                  title: "",
                  description: ""
        },

        initialize: function() {
            console.log ("New Company Created");
        }
    });

    var Search = Backbone.Collection.extend({
        url: '/api/companies',
        model: Company
    })

    var s = new Search();

    s.fetch();
})(jQuery);

Mockjax.js

$.mockjax({
    url: '\/api\/companies',
    contentType: 'text/json',
    responseTime: 150,
    type: 'GET',
    response: function (settings) {
        "use strict";
        this.responseText = [];

        for ( var i=0; i<=100; i++) {
            this.responseText.push({ title: "Title " + i, description: "Description"})
        }

    }
})

这就是我执行它时发生的情况:

GET http://localhost:63342/api/companies 404 (Not Found) jquery.js:8526
XHR finished loading: "http://localhost:63342/api/companies". 

但如果我在控制台中执行$.get('/api/companies');,我会正确理解:

$.get('/api/companies');
MOCK GET: /api/companies 
Object {url: "/api/companies", type: "get", isLocal: false, global: true, processData: true…}
 jquery.mockjax.js:546
Object {readyState: 1, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}

知道为什么会这样吗?

【问题讨论】:

    标签: javascript jquery json backbone.js


    【解决方案1】:

    你可以试试这个方法:http://japhr.blogspot.in/2011/10/overriding-url-and-fetch-in-backbonejs.html

    我想对你有帮助

     var Appointments = Backbone.Collection.extend({
              model: Models.Appointment,
              initialize: function(options) {
                options || (options = {});
                this.date = options.date;
              },
              url: function () {
                return '/appointments/' + this.date;
              },
              setDate: function(date) {
                this.date = date;
                this.fetch();
              },
              parse: function(response) {
                return _(response.rows).map(function(row) { return row.value ;});
              }
            });
    

    【讨论】:

    【解决方案2】:

    这是一个 jQuery.mockjax 错误,而不是 Backbone。它被严重包含在 HTML 中的错误位置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-02
      • 1970-01-01
      • 2023-01-28
      • 2021-08-05
      相关资源
      最近更新 更多