Backbone.js recupera con parametri


152

A seguito della documentazione , ho fatto:

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

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

l'URL si è rivelato essere: http://localhost:1273/Items?[object%20Object]

Mi aspettavo qualcosa di simile http://localhost:1273/Items?page=1

Quindi, come faccio a passare i parametri nel metodo fetch?


È decisamente strano. Quello che sembra dovrebbe funzionare bene, in base ai documenti API . Stai utilizzando l'ultima versione di Backbone.js?
Matt Ball,

Puoi provare JSON.stringify({ data: { page: 1} })?
Joe,

@Joe Tuskan, non sono sicuro di cosa farsene, ma l'ho fatto: collection.fetch(JSON.stringify({ data: { page: 1} }));e nulla è stato passato nell'URL.
Shawn Mclean,

Ok, fai questo: collection.fetch ({data: JSON.stringify ({pagina: 1})});
Joe,

3
Funziona bene come l'hai scritto in Backbone 1.0 fyi
Dominic

Risposte:


213

mutevole:

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

per:

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

Quindi, senza farlo, questo viene chiamato con il tuo {data: {page:1}}oggetto comeoptions

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

Quindi invia i "dati" a jQuery.ajax che farà del suo meglio per aggiungere qualunque cosa params.datasia all'URL.


71

Puoi anche impostare processData su true:

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

Jquery elaborerà automaticamente l'oggetto dati in una stringa param,

ma nella funzione Backbone.sync, Backbone disattiva processData perché Backbone utilizzerà altri metodi per elaborare i dati in POST, UPDATE ...

nella fonte Backbone:

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


-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);
}
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.