Javascript 轨道&x2B;JS+;Ajax请求
大家好,我正在用Rails+JS+Ajax制作游戏《where is Waldo(Wally)》的简单克隆。这个想法是:玩家变成3个图像,并且必须检查3个角色(沃尔多、威尔玛、巫师)的位置。三点以后。图像显示提交名称的字段,提交后显示高分列表 到目前为止,我已经为时间(JS变量和setInterval)、点(JS+AJAX+rails控制器)编写了机制代码,但我无法为提交名称、点和时间模型编写操作代码 我的视图文件:Javascript 轨道&x2B;JS+;Ajax请求,javascript,ruby-on-rails,ajax,Javascript,Ruby On Rails,Ajax,大家好,我正在用Rails+JS+Ajax制作游戏《where is Waldo(Wally)》的简单克隆。这个想法是:玩家变成3个图像,并且必须检查3个角色(沃尔多、威尔玛、巫师)的位置。三点以后。图像显示提交名称的字段,提交后显示高分列表 到目前为止,我已经为时间(JS变量和setInterval)、点(JS+AJAX+rails控制器)编写了机制代码,但我无法为提交名称、点和时间模型编写操作代码 我的视图文件: <%= form_tag('/check/highscore', me
<%= form_tag('/check/highscore', method: :post, format: :js, remote: true ) do %>
<%= text_field_tag 'name', 'enter your name' %>
<%= submit_tag 'submit' %>
<% end %>
<script type="text/javascript">
$.ajax({
url: "<%= highscore_check_index_path %>",
type: "POST",
format: "js",
dataType: "script",
data: { username: $(this).username, score: guessd, time: time },
success: function(data) {
$('send_highscore').append('data.username')
window.waldo.HS()
},
});
};
my highscore.js.erb
console.log("<%=j @username %>");
window.waldo.HS = function(username) {
$.ajax({
url: "<%= highscore2_check_index_path %>",
type: "POST",
format: "js",
data: { username: name, score: guessd, time: time },
success: function(data) {
console.log(data);
$('send_highscore').append('data.username')
}
});
});
console.log(“”);
window.waldo.HS=函数(用户名){
$.ajax({
url:“”,
类型:“POST”,
格式:“js”,
数据:{用户名:名称,分数:猜测,时间:时间},
成功:功能(数据){
控制台日志(数据);
$('send_highscore').append('data.username'))
}
});
});
我知道,我的书质量很差,但我现在试着去学。问题是highscore.js.erb并没有执行,尽管我在firebug中看到它被渲染为js脚本文件。
highscore.js.erb的思想是混合ruby和js变量,并在check controller中一起发送highscore2操作并保存到db js.erb是一种糟糕的学习方式。
通过使用remote:true
并返回JS.erb响应,RubyonRails可以用作穷人的单页架构。但它所做的一切都给了你足够的绳子来吊死自己
这是一种非常糟糕的学习ajax的方法,因为它会导致糟糕的代码组织和非常非RESTful的应用程序,因为它会导致关注过程而不是资源
相反,我鼓励您尝试学习ajax,而不要混合使用ERB和JS。混合使用服务器端和客户端逻辑只会使一切变得更加复杂,因为您必须跟踪在哪里发生的事情
相反,您可能希望专注于在app/assets/javascripts
中设置可重用的javascript函数,并获取JSON数据,而不是javascript过程
这不仅将教会您在Rails中使用ajax,还将教会您如何使用外部API来使用ajax,并教会您如何构造和组织代码
让我们开始看看如何重构:
高分应该是一种资源
让我们从设置路由开始:
resources :highscores, only: [:create, :index, :show]
以及控制器:
class HighscoresController < ApplicationController
respond_to :json, :html
def create
@highscore = Highscore.create(highscore_params)
respond_with @highscore
end
def index
@highscores = Highscore.order(score: :desc).all
respond_with @highscores
end
def show
@highscore = Highscore.find(params[:id])
respond_with @highscore
end
private
def highscore_params
params.require(:highscore).permit(:username, :time, :score)
end
end
然后将这一小块添加到applicationon.js
:
// Triggers events based on the current controller and action.
// Example:
// given the controller UsersController and the action index
// users:loaded
// users.index:loaded
$(document).on('page:change', function(){
var data = $('body').data();
$(this).trigger(data.controller + ":loaded")
.trigger(data.controller + "." + data.action + ":loaded");
});
你们谈论的阿贾克斯在哪里?
假设我们有一个高分列表,我们希望定期(轮询)或在用户提交高分时更新该列表
// app/assets/javascripts/highscores.js
function getHighscores(){
var $self = $('.highscores-list');
return $.getJSON('/highscores').done(function(highscores){
var elements = $.map(highscores, function(h){
return $('<li>').text([h.username, h.score].join(', '));
});
$self.empty().append(elements);
});
};
$(document).on('games:loaded highscores:loaded', function(){
// refresh highscores every 5 seconds
(function refresh(){
getHighscores().done(function(){
window.setTimeout(refresh, 5000);
});
}());
});
然后让我们用一些ajax的优点来描述它:
$(document).on('games:loaded highscores:loaded', function(){
$('#new_highscore').submit(function(e){
$.ajax(this.action, {
data: {
highscore: {
username: this.elements["highscore[username]"].value,
time: this.elements["highscore[time]"].value,
score: this.elements["highscore[score]"].value
}
},
method: 'POST',
dataType: 'JSON'
}).done(function(data, status, jqXHR){
getHighscores();
// todo notify user
});
return false; // prevent form from being submitted normally
});
});
尝试用
$(document.ready()
包装它。我已经尝试过了,但没有改变任何东西。我无法在控制台中调用函数window.waldo.HS()。是否有任何错误?。如果有共享…同时,您是否启用了turbolinks
?此处提供了完整示例。请注意,为了简洁起见,这使用了全局函数——我将让您来模块化它。谢谢您的精彩回答!我在自学RoR。到目前为止,这对我来说非常简单,但是使用JS+AJAX+RoR的合适方式对我来说并不明显。你的帖子对我来说简单了一点,但今天我已经厌倦了打击它,明天我会严厉处理它;)。你知道一本好书或是资源吗?我能在哪里读到更多关于这个话题的内容吗?真的很抱歉,我在阅读和阅读John Resig和道格拉斯克罗克福德的许多博客文章和谈话时,并没有真正拥有一本书。嗨,今天我有时间和力量去考虑它应该工作,我理解它。但是我不知道表单如何获得我保存为javascript变量的时间和分数值,例如timescript
:$(document.ready)(function(){
time=0;
window.timer();
})
window.timer=function(){
time++;
timerVar=window.setTimeout(window.timer,1000);
>代码>只需更改表单输入的值。例如$(“#highscore_score”).val(500)
。
// app/assets/javascripts/highscores.js
function getHighscores(){
var $self = $('.highscores-list');
return $.getJSON('/highscores').done(function(highscores){
var elements = $.map(highscores, function(h){
return $('<li>').text([h.username, h.score].join(', '));
});
$self.empty().append(elements);
});
};
$(document).on('games:loaded highscores:loaded', function(){
// refresh highscores every 5 seconds
(function refresh(){
getHighscores().done(function(){
window.setTimeout(refresh, 5000);
});
}());
});
<%# app/views/highscores/_form.html.erb %>
<%= form_for(local_assigns[:highscore] || Highscore.new), class: 'highscore-form' do |f| %>
<div class="field">
<%= f.label :username %>
<%= f.text_field :username %>
</div>
<%= f.hidden_field :score %>
<%= f.hidden_field :time %>
<%= f.submit %>
<% end %>
$(document).on('games:loaded highscores:loaded', function(){
$('#new_highscore').submit(function(e){
$.ajax(this.action, {
data: {
highscore: {
username: this.elements["highscore[username]"].value,
time: this.elements["highscore[time]"].value,
score: this.elements["highscore[score]"].value
}
},
method: 'POST',
dataType: 'JSON'
}).done(function(data, status, jqXHR){
getHighscores();
// todo notify user
});
return false; // prevent form from being submitted normally
});
});