sinatra输出params到文本文件?

时间:2017-04-19 17:06:28

标签: javascript ruby ajax sinatra

我试图使用此代码将ajax paramas输出到文本文件但不起作用

我不知道,因为它不起作用

我将此代码用于打印参数

f.write params [:name]

require 'sinatra'
require 'pp'

get '/' do
  erb :index
end



get '/2' do
  content_type 'text/javascript'
  File.read(File.join('public', 'jquery-1.7.1.js'))

end


post '/greeting' do
  puts "params"
  #pp params

  "<p>#{params[:salutation]}, #{params[:name]}</p>"
end


post '/greeting' do
   puts "params"
  #pp params
  File.read(File.join('public', 'name_of_the_file.txt'))
  File.open('name_of_the_file.txt', 'w') do |f|
    f.write params[:name]
  end
end

ZZ

<html>
  <head>
    <script src="/2"></script>
    <script type="text/javascript">
      $(document).ready(function() {
ax=2;
$('body').on("click   reset",function(e){  ax= e.target.value ; }); 
ax=2;
        $.post("greeting", { salutation:  ax, name: "Friend" },
          function(result) { $("#greeting").html(result);
        });
      });
    </script>
  </head>
  <body>
    <h1>Sinatra Ajax Demo using jQuery</h1>
<label for="male">Male</label>
  <input type="radio" name="gender" id="male" value="male"><br>
  <label for="female">Female</label>
  <input type="radio" name="gender" id="female" value="female"><br>
  <label for="other">Other</label>
  <input type="radio" name="gender" id="other" value="other"><br><br>
  <input type="submit" value="Submit">
    <div id="greeting">
      <p>Hello, World</p>
    </div>
  </body>
</html>

请帮助我解决这个问题

1 个答案:

答案 0 :(得分:0)

我用这个解决了

f = File.open('text.txt', 'w')

old_out = $stdout
$stdout = f

  puts   params[:salutation] 
f.close

$stdout = old_out
puts 'goodbye'