我目前正在做一个项目,在这个项目中,我在输入框中键入一个关键字,当我单击“发送”时,它会通过一个类似于 (localhost/json-status.php?query=input text ),它以 json 格式返回“query=”之后的任何内容。现在我已经用 jQuery 完成了这个,我正在尝试在 backbone js 中再次做这个。
$("#updateStatus").click(function(){
var query = $("#statusBar").val();
var url = "json-status.php" + "?query=" + query;
$.getJSON(url,function(json){
$.each(json.posts,function(i,post){
$("#content").append(
'<div>'+
'<p>'+post.status+'</p>'+
'</div>'
);
});
});
});
我已经将我在 jQuery 中所做的大部分移植到 Backbone js 中,但到目前为止它没有按预期工作,请告诉我我的方法是否正确以及我如何解决我的问题。
Backbone 代码:
(function ($) {
Status = Backbone.Model.extend({
status: null
});
StatusList = Backbone.Collection.extend({
initialize: function (models, options) {
this.bind("add", options.view.addStatusList);
}
});
AppView = Backbone.View.extend({
el: $("body"),
initialize: function () {
this.status = new StatusList( null, { view: this });
},
events: {
"click #updateStatus": "getStatus",
},
getStatus: function () {
var url = "json-status.php" + "?query=" + $("#statusBar").val();
var statusModel;
$.getJSON(url,function(json){
$.each(json.posts,function(i,post){
statusModel = new Status({ status: post.status });
this.status.add( statusModel );
});
});
},
addStatusList: function (model) {
$("#status").prepend("<div>" + model.get('status') + "</div>");
}
});
var appview = new AppView;
})(jQuery);
以 json 格式返回的 PHP 服务器代码(这很好用):
<?php
$getQuery = $HTTP_GET_VARS["query"];
$json='
{"posts":[
{
"status": "' . $getQuery . '"
}
]}
';
echo $json;
?>
如果你想复制/粘贴我到目前为止的内容:
<!DOCTYPE html>
<html>
<head>
<title>JSON Test</title>
</head>
<body>
<input value="What's on your mind?" id="statusBar" /><button id="updateStatus">Update Status</button>
<div id="content">
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>
<script type="text/javascript">
$("#statusBar").click(function() {
$(this).val("");
});
(function ($) {
Status = Backbone.Model.extend({
status: null
});
StatusList = Backbone.Collection.extend({
initialize: function (models, options) {
this.bind("add", options.view.addStatusList);
}
});
AppView = Backbone.View.extend({
el: $("body"),
initialize: function () {
this.status = new StatusList( null, { view: this });
},
events: {
"click #updateStatus": "getStatus",
},
getStatus: function () {
var url = "json-status.php" + "?query=" + $("#statusBar").val();
var statusModel;
$.getJSON(url,function(json){
$.each(json.posts,function(i,post){
statusModel = new Status({ status: post.status });
this.status.add( statusModel );
});
});
},
addStatusList: function (model) {
$("#status").prepend("<div>" + model.get('status') + "</div>");
}
});
var appview = new AppView;
})(jQuery);
</script>
</body>
</html>
感谢您的宝贵时间。
朱利安的代码。
StatusList = Backbone.Collection.extend({
model: Status,
value: null,
url: function(){ return "json-status.php?query=" + this.value;}
});
AppView = Backbone.View.extend({
el: $("body"),
initialize: function () {
_.bindAll(this, "render");// to solve the this issue
this.status = new StatusList( null, { view: this });
this.status.bind("refresh", this.render);
},
events: {
"click #updateStatus" :"getStatus",
},
getStatus: function () {
this.status.value = $("#statusBar").val();
this.status.fetch(this.status.value);
},
render: function () {
var statusEl = $("#status");
this.status.each( function(model) {
statusEl.prepend("<div>" + model.get('status') + "</div>");
});
}
});
var appview = new AppView;
完整的 HTML(第 2 部分):
<!DOCTYPE html>
<html>
<head>
<title>JSON Test</title>
</head>
<body>
<input value="What's on your mind?" id="statusBar" />
<button id="updateStatus">Update Status</button>
<div id="status">
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>
<script type="text/javascript">
$("#statusBar").click(function() {
$(this).val("");
});
Status = Backbone.Model.extend();
StatusList = Backbone.Collection.extend({
model: Status,
value: null,
url: function(){ return "json-status.php?query=" + this.value;}
});
AppView = Backbone.View.extend({
el: $("body"),
initialize: function () {
_.bindAll(this, "render");// to solve the this issue
this.status = new StatusList( null, { view: this });
this.status.bind("refresh", this.render);
},
events: {
"click #updateStatus" :"getStatus",
},
getStatus: function () {
this.status.value = $("#statusBar").val();
this.status.fetch(this.status.value);
},
render: function () {
var statusEl = $("#status");
this.status.each( function(model) {
statusEl.prepend("<div>" + model.get('status') + "</div>");
});
}
});
var appview = new AppView;
</script>
</body>
</html>
并且 PHP 仍然与最初记录的相同。
最佳答案
至于您的总体设计,您应该使用Backbone.Model 和Collection 来获取您的状态:
Status = Backbone.Model.extend();
StatusList = Backbone.Collection.extend({
model: Status,
value: null
url: function(){ return "json-status.php" + "?query=" + this.value;
});
您的 View 应该监听 StatusList,而不是 StatusList 创建到 View 的绑定(bind):
AppView = Backbone.View.extend({
el: $("body"),
initialize: function () {
_.bindAll(this, "render");// to solve the this issue
this.status = new StatusList( null, { view: this });
this.status.bind("refresh", this.render);
},
events: {
"click #updateStatus": "getStatus",
},
getStatus: function () {
this.status.value = $("#statusBar").val();
this.status.fetch()
},
render: function () {
var statusEl = $("#status")
this.status.each( function(model){
statusEl.prepend("<div>" + model.get('status') + "</div>");
}
}
});
这里有两件事:
关于javascript - 将 JSON 提要与 Backbone JS 集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5629972/
在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这
我在app/helpers/sessions_helper.rb中有一个帮助程序文件,其中包含一个方法my_preference,它返回当前登录用户的首选项。我想在集成测试中访问该方法。例如,这样我就可以在测试中使用getuser_path(my_preference)。在其他帖子中,我读到这可以通过在测试文件中包含requiresessions_helper来实现,但我仍然收到错误NameError:undefinedlocalvariableormethod'my_preference'.我做错了什么?require'test_helper'require'sessions_hel
我一直很高兴地使用DelayedJob习惯用法:foo.send_later(:bar)这会调用DelayedJob进程中对象foo的方法bar。我一直在使用DaemonSpawn在我的服务器上启动DelayedJob进程。但是...如果foo抛出异常,Hoptoad不会捕获它。这是任何这些包中的错误...还是我需要更改某些配置...或者我是否需要在DS或DJ中插入一些异常处理来调用Hoptoad通知程序?回应下面的第一条评论。classDelayedJobWorker 最佳答案 尝试monkeypatchingDelayed::W
我有一个非常简单的RubyRack服务器,例如:app=Proc.newdo|env|req=Rack::Request.new(env).paramspreq.inspect[200,{'Content-Type'=>'text/plain'},['Somebody']]endRack::Handler::Thin.run(app,:Port=>4001,:threaded=>true)每当我使用JSON对象向服务器发送POSTHTTP请求时:{"session":{"accountId":String,"callId":String,"from":Object,"headers":
前置步骤我们都操作完了,这篇开始介绍jenkins的集成。话不多说,看操作1、登录进入jenkins后会让你选择安装插件,选择第一个默认的就行。安装完成后设置账号密码,重新登录。2、配置JDK和Git都需要执行路径,所以需要先把执行路径找到,先进入服务器的docker容器,2.1JDK的路径root@69eef9ee86cf:/usr/bin#echo$JAVA_HOME/usr/local/openjdk-82.2Git的路径root@69eef9ee86cf:/#whichgit/usr/bin/git3、先配置JDK和Git。点击:ManageJenkins>>GlobalToolCon
我正在使用ruby2.1.0我有一个json文件。例如:test.json{"item":[{"apple":1},{"banana":2}]}用YAML.load加载这个文件安全吗?YAML.load(File.read('test.json'))我正在尝试加载一个json或yaml格式的文件。 最佳答案 YAML可以加载JSONYAML.load('{"something":"test","other":4}')=>{"something"=>"test","other"=>4}JSON将无法加载YAML。JSON.load("
我遇到了一个非常奇怪的问题,我很难解决。在我看来,我有一个与data-remote="true"和data-method="delete"的链接。当我单击该链接时,我可以看到对我的Rails服务器的DELETE请求。返回的JS代码会更改此链接的属性,其中包括href和data-method。再次单击此链接后,我的服务器收到了对新href的请求,但使用的是旧的data-method,即使我已将其从DELETE到POST(它仍然发送一个DELETE请求)。但是,如果我刷新页面,HTML与"new"HTML相同(随返回的JS发生变化),但它实际上发送了正确的请求类型。这就是这个问题令我困惑的
我在一个简单的RailsAPI中有以下Controller代码:classApi::V1::AccountsControllerehead:not_foundendendend问题在于,生成的json具有以下格式:{id:2,name:'Simpleaccount',cash_flows:[{id:1,amount:34.3,description:'simpledescription'},{id:2,amount:1.12,description:'otherdescription'}]}我需要我生成的json是camelCase('cashFlows'而不是'cash_flows'
我正在学习如何使用JSONgem解析和生成JSON。我可以轻松地创建数据哈希并将其生成为JSON;但是,在获取一个类的实例(例如Person实例)并将其所有实例变量放入哈希中以转换为JSON时,我脑袋放屁。这是我遇到问题的例子:require"json"classPersondefinitialize(name,age,address)@name=name@age=age@address=addressenddefto_jsonendendp=Person.new('JohnDoe',46,"123ElmStreet")p.to_json我想创建一个.to_json方法,这样我就可以获
我正在构建一个带有Rails后端的JS应用程序,为了不混淆snake和camelcases,我想通过从服务器返回camelcase键名来规范化这一切。因此,当从API返回时,user.last_name将返回user.lastName。我如何实现这一点?谢谢!编辑:添加Controller代码classApi::V1::UsersController 最佳答案 我的方法是使用ActiveModelSerializer和json_api适配器:在你的Gemfile中,添加:gem'active_model_serializers'创建