Backbone.js使用参数获取

时间:2011-07-12 03:48:53

标签: javascript backbone.js

documentation之后,我做了:

var collection = new Backbone.Collection.extend({
        model: ItemModel,
        url: '/Items'
})

collection.fetch({ data: { page: 1} });

网址原来是:http://localhost:1273/Items?[object%20Object]

我期待http://localhost:1273/Items?page=1

之类的东西

那么如何在fetch方法中传递params?

4 个答案:

答案 0 :(得分:212)

改变:

collection.fetch({ data: { page: 1} });

到:

collection.fetch({ data: $.param({ page: 1}) });

因此,如果不执行此操作,则会将{data: {page:1}}对象调用为options

Backbone.sync = function(method, model, options) {
    var type = methodMap[method];

    // Default JSON-request options.
    var params = _.extend({
      type:         type,
      dataType:     'json',
      processData:  false
    }, options);

    // Ensure that we have a URL.
    if (!params.url) {
      params.url = getUrl(model) || urlError();
    }

    // Ensure that we have the appropriate request data.
    if (!params.data && model && (method == 'create' || method == 'update')) {
      params.contentType = 'application/json';
      params.data = JSON.stringify(model.toJSON());
    }

    // For older servers, emulate JSON by encoding the request into an HTML-form.
    if (Backbone.emulateJSON) {
      params.contentType = 'application/x-www-form-urlencoded';
      params.processData = true;
      params.data        = params.data ? {model : params.data} : {};
    }

    // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
    // And an `X-HTTP-Method-Override` header.
    if (Backbone.emulateHTTP) {
      if (type === 'PUT' || type === 'DELETE') {
        if (Backbone.emulateJSON) params.data._method = type;
        params.type = 'POST';
        params.beforeSend = function(xhr) {
          xhr.setRequestHeader('X-HTTP-Method-Override', type);
        };
      }
    }

    // Make the request.
    return $.ajax(params);
};

因此,它会将“数据”发送给jQuery.ajax,这会尽力将params.data附加到网址。

答案 1 :(得分:71)

您还可以将processData设置为true:

collection.fetch({ 
    data: { page: 1 },
    processData: true
});

Jquery会自动将数据对象处理为param字符串,

但在Backbone.sync函数中, Backbone将关闭processData,因为Backbone将使用其他方法来处理数据 在POST,UPDATE ......

在Backbone来源:

if (params.type !== 'GET' && !Backbone.emulateJSON) {
    params.processData = false;
}

答案 2 :(得分:1)

如果您使用钛合金的另一个例子:

 collection.fetch({ 
     data: {
             where : JSON.stringify({
                page: 1
             })
           } 
      });

答案 3 :(得分:-2)

try {
    // THIS for POST+JSON
    options.contentType = 'application/json';
    options.type = 'POST';
    options.data = JSON.stringify(options.data);

    // OR THIS for GET+URL-encoded
    //options.data = $.param(_.clone(options.data));

    console.log('.fetch options = ', options);
    collection.fetch(options);
} catch (excp) {
    alert(excp);
}