使用搜索参数获取 Backbone 集合 [英] Fetch Backbone collection with search parameters

查看:9
本文介绍了使用搜索参数获取 Backbone 集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 Backbone.js 实现一个搜索页面.搜索参数取自一个简单的形式,服务器知道解析查询参数并返回结果的 json 数组.我的模型或多或少是这样的:

I'd like to implement a search page using Backbone.js. The search parameters are taken from a simple form, and the server knows to parse the query parameters and return a json array of the results. My model looks like this, more or less:

App.Models.SearchResult = Backbone.Model.extend({
    urlRoot: '/search'
});

App.Collections.SearchResults = Backbone.Collection.extend({
    model: App.Models.SearchResult
});

var results = new App.Collections.SearchResults();

我希望每次执行 results.fetch() 时,搜索表单的内容也将与 GET 请求一起序列化.是否有一种简单的方法来添加它,或者我是否以错误的方式进行了操作,并且可能应该对请求进行手动编码并从返回的结果中创建集合:

I'd like that every time I perform results.fetch(), the contents of the search form will also be serialized with the GET request. Is there a simple way to add this, or am I doing it the wrong way and should probably be handcoding the request and creating the collection from the returned results:

$.getJSON('/search', { /* search params */ }, function(resp){
    // resp is a list of JSON data [ { id: .., name: .. }, { id: .., name: .. }, .... ]
    var results = new App.Collections.SearchResults(resp);

   // update views, etc.
});

想法?

推荐答案

Backbone.js fetch with参数回答了你的大部分问题,但我也在这里放了一些.

Backbone.js fetch with parameters answers most of your questions, but I put some here as well.

data 参数添加到您的 fetch 调用中,例如:

Add the data parameter to your fetch call, example:

var search_params = {
  'key1': 'value1',
  'key2': 'value2',
  'key3': 'value3',
  ...
  'keyN': 'valueN',
};

App.Collections.SearchResults.fetch({data: $.param(search_params)});

现在您的调用 url 添加了参数,您可以在服务器端解析这些参数.

Now your call url has added parameters which you can parse on the server side.

这篇关于使用搜索参数获取 Backbone 集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆