我正在尝试构建一个RubyOnRails应用程序,该应用程序最终将使用discogs api gem显示有关列表的获取信息。现在,我只是想编写一个成功的Ajax示例,一旦按下按钮,该示例将替换页面上的文本。我的代码如下:
index.html.erb
<%= javascript_include_tag "application" %>
<h1>Welcome to my website#index</h1>
<input class="className" id="idName" type="button" value="Click Me!" id="my_button" remote:true/>
<ul id="ulID">
<div class = 'wantToChange'>This should change when button is pressd.</div>
</ul>
application.js
$(document).ready(function(){
$('.className').on('click', function(){
console.log("inside js click listener");
var capture = "temp";
$.ajax({
type:'POST',
url:'test',
dataType:"json",
data: {some_parameter: 'hellothere'},
success: function(data) {
capture = data;
}
});
console.log("\n capture = ", capture)
});
});
routes.rb
Rails.application.routes.draw do
get 'welcome/index'
resources :test do
collection do
get 'test'
end
end
root 'welcome#index'
end
welcome_controller.rb
class WelcomeController < ApplicationController
def index
end
def test
some_parameter = params[:some_parameter]
#do something with some_parameter and return the results
end
end
现在使用这些文件,我只是想使其制作成这样,所以当我单击按钮时,它会进行ajax调用,该调用会向我的javascript函数返回一个新字符串。我认为控制器/ ajax请求中的某些内容并不太正确,因为当我单击按钮时,eventlistener可以工作并最初打印“ temp”,但是第二次打印“ temp”,表明我的ajax调用没有正确返回新字符串。