Backbone.js使用参数获取

2020/11/08 19:42 · javascript ·  · 0评论

根据文档,我做了:

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方法中传递参数呢?

改变:

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内容附加到URL。

您还可以将processData设置为true:

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

jQuery会将数据对象自动处理为参数字符串,

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

在主干源中:

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

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

 collection.fetch({ 
     data: {
             where : JSON.stringify({
                page: 1
             })
           } 
      });
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);
}
本文地址:http://javascript.askforanswer.com/backbone-jsshiyongcanshuhuoqu.html
文章标签: ,  
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!