Backbone.js fetch con parámetros

152

Siguiendo la documentación , hice:

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

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

la url resultó ser: http://localhost:1273/Items?[object%20Object]

Esperaba algo como http://localhost:1273/Items?page=1

Entonces, ¿cómo paso parámetros en el método fetch?

Shawn Mclean
fuente
Eso es definitivamente raro. Parece que lo que tiene debería funcionar bien, según los documentos de la API . ¿Estás utilizando la última versión de Backbone.js?
Matt Ball
Se puede tratar JSON.stringify({ data: { page: 1} })?
Joe
@ Joe Tuskan, no estoy seguro de qué hacer con eso, pero lo hice: collection.fetch(JSON.stringify({ data: { page: 1} }));y no se pasó nada en la url.
Shawn Mclean
Ok, haga esto: collection.fetch ({data: JSON.stringify ({page: 1})});
Joe
3
Esto funciona bien como lo escribió en Backbone 1.0 fyi
Dominic

Respuestas:

213

cambiando:

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

a:

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

Entonces, sin hacerlo, esto se llama con su {data: {page:1}}objeto comooptions

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);
};

Por lo tanto, envía los 'datos' a jQuery.ajax, que hará todo lo posible para agregar lo que params.datasea ​​a la URL.

Joe
fuente
71

También puede establecer processData en true:

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

Jquery procesará automáticamente el objeto de datos en una cadena param,

pero en la función Backbone.sync, Backbone apaga el processData porque Backbone usará otro método para procesar datos en POST, UPDATE ...

en la fuente Backbone:

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

Otro ejemplo si está utilizando aleación de titanio:

 collection.fetch({ 
     data: {
             where : JSON.stringify({
                page: 1
             })
           } 
      });
peponline
fuente
1
¿Qué es la aleación de titanio?
Neil
Alloy es un marco MVC para Appcelerator Titanium SDK ( github.com/appcelerator/alloy )
peponline el
-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);
}
Walter von Entferndt
fuente