用javascript调用函数fron-ruby控制器

call function fron ruby controller in javascript

本文关键字:fron-ruby 控制器 函数 调用 javascript      更新时间:2023-09-26

我想对controllers/static_pages_controller.rb:中的文件执行写入操作

def fileopen
        my_file = File.new("public/CHNAME1.txt","w") 
        my_file.write "'tfasf"
        my_file.close
    end

(当我在助手中定义它并在视图中调用它时,它工作得很好。)

在myview.html.erb中,我想要一些类似"我该怎么做?"?我在application.js 中尝试过

function readfile() {
  alert('readfile work')
  $.ajax({
  alert('ajax work')
      url: "/fileopen",
      type: "POST",
      ##don't know what to to to call fileopen
      }
  });
}

routes.rb

match '/fileopen', to:'static_pages#fileopen', via: 'get'

似乎什么都没发生。只有第一个警报工作

您有语法错误,请尝试以下操作:

function readfile() {
  alert('readfile work');
  $.ajax({
      url: "/fileopen",
      type: "POST",
      success: function(){
          alert('ajax work');
      }
  });
}

我不知道ruby,但路由是在"GET"请求上,而您正在发出"POST"请求:

match '/fileopen', to:'static_pages#fileopen', via: 'get' // should be via: 'post'?

您不能在ajax中使用alert,如果您想使用它,则在成功和错误方法中使用