我想在rails应用程序中发出ajax post请求.但我得到的回应是错误的. Rails代码: – def search_exams(myparam1 , myparam2) json_data = {:aaData= [["abc","xyz","lmnop"],["sdf","adsdf","sadfsd"],["sdf","adsdf","sadfsd"]]}.
Rails代码: –
def search_exams(myparam1 , myparam2) json_data = {:aaData=> [["abc","xyz","lmnop"],["sdf","adsdf","sadfsd"],["sdf","adsdf","sadfsd"]]}.to_json respond_to do |format| format.json { render :json => json_data } end end
脚本代码: –
<%= javascript_tag "window._token = '#{form_authenticity_token}'" %> <script> $.ajax({ url:'/home/search_exams', type:'POST', dataType:'json', data:{ myparam1: "First Param value", myparam2: "Second param value", authenticity_token: window._token }, success:function(data){ debugger; }, error:function(data){ debugger; } }); </script>
我收到这个错误: –
“HomeController中的ArgumentError#search_exams错误的参数数量(0表示2)Rails.root:C:/ Users / ……..”
def search_exams
从方法中删除参数.
当您将带有params的请求传递给Rails控制器时,中间件堆栈会将它们放入params散列中,因此您将得到:
params[:param1] params[:params2]
–
您还需要考虑制作JS unobtrusive:
#app/assets/javascripts/application.js $(document).on("action", ".element", function(){ $.ajax({ url:'/home/search_exams', type:'POST', dataType:'json', data:{ myparam1: "First Param value", myparam2: "Second param value", authenticity_token: window._token }, success:function(data){ debugger; }, error:function(data){ debugger; } }); });