我有一个以Codeingiter为后端的Backbone App。我使用RESTful应用程序接口设置在这些框架之间来回传递数据。
现在我想要一个显示“最新追随者”的视图,为此我创建了一个API,如下所示:
public function new_artist_followers_get($start_date, $end_date)
{
$this->load->database();
$sql = "SELECT users.img_name FROM artist_followers INNER JOIN artists ON artists.artist_id = artist_followers.artist_id INNER JOIN users ON users.user_id = artist_followers.user_id
WHERE artist_followers.artist_id = artists.artist_id AND date_time BETWEEN '$start_date' AND '$end_date' LIMIT 20";
$query = $this->db->query($sql);
$data = $query->result();
if($data) {
$this->response($data, 200);
} else {
$this->response(array('error' => 'Couldn\'t find any artist followers!'), 404);
}
}我的问题是,我真的不确定如何将日期传递到我的骨干前端?我一定要这样做吗?:
NewFollowers.NewFollowersCollection = Backbone.Collection.extend({
url: function() {
return '/projects/testproject/index.php/api/testfile/new_artist_followers/'+ this.artist_id + this.startdate + this.enddate;
}
});通常,我获取一个与上面示例完全一样的API,只是没有this.startdate和this.enddate,然后在我的MainView中收集所有东西,其中我为每个API/Collection执行此操作(在本例中是艺术家传记):
beforeRender: function() {
var artistbioCollection = new Artistbio.ArtistbioCollection();
artistbioCollection.artist_id = this.artist_id;
this.insertView('.artistBio', new Artistbio.View({collection: artistbioCollection}));
artistbioCollection.fetch();
....etc. etc. ...}
有人能帮我吗?
发布于 2014-03-02 01:03:45
Backbone.Collection fetch方法接受额外的参数,它们应该像这样传递:
artistbioCollection.fetch({
data: {
start_date: this.startdate,
end_date: this.enddate
}
});它是Backbone documentation格式的
因此,在这里,data是与jQuery.ajax data属性相同的属性,然后您可以像往常一样在服务器端获取这些值。
当fetch执行GET请求时,传递给data的所有参数都将附加到查询字符串中
发布于 2014-03-02 02:44:29
您应该使用URI模板在服务器端定义URI,如下所示:
http://example.com/api{/artist,id}/followers{?stardate,enddate}在此之后,您可以使用例如this library在客户端使用参数填充此模板。您可以为这些参数添加自定义设置器,例如(未测试):
NewFollowers.NewFollowersCollection = Backbone.Collection.extend({
url: function() {
return URI.expand("http://example.com/api{/artist,artistId}/followers{?startDate,endDate}", this.params).href();
},
setParams: function (artist, start, end){
this.params = {
artistId: artist.get("id"),
startDate: start,
endDate: end
};
}
});请注意,这不是一个完整的REST解决方案。通过REST,您可以获得超媒体响应,其中包含链接。其中一个链接可以包含实际的URI模板和参数描述。因此,您的客户端与URI结构完全解耦,它不知道如何构建URI,但它知道如何计算URI模板,这是一个标准的解决方案。您可以使用标准解决方案将客户端与服务的实现解耦,这称为REST的统一接口约束。
https://stackoverflow.com/questions/22095580
复制相似问题