简体   繁体   English

如何从JavaScript发送GET请求到rails

[英]How to send GET request to rails from javascript

I've been googling all day and still couldn't find any answers.So basically in my javascript function, I want to send a GET request to my rails controller and the rails controller will send back a JSON object. 我一整天都在谷歌搜索,但仍然找不到任何答案。所以基本上在我的javascript函数中,我想向我的rails控制器发送一个GET请求,并且rails控制器将发回一个JSON对象。 Any idea how do I do this? 知道我该怎么做? thnx 日Thnx

Using jQuery I would do something like this: 使用jQuery我会做这样的事情:

In the selector and event you want, for instance on clicking some element: 在您想要的选择器和事件中,例如在单击某个元素时:

 $(function() { $('#foo').click( function(){ var params = '{"field1": "value1", "field2: "value2"}'; $.get('/controller/bar', params, function(data){ alert(data); }); }); }); 

Then in your Rails controller: 然后在你的Rails控制器中:

 def bar /// hack hack hack render :json => {"response" => "OK"} end 

The in your routes.rb: 你的routes.rb中:

  match 'controller/bar' => 'controller#bar'

Finally, change "controller" according to your code. 最后,根据您的代码更改“控制器”。 Firebug is your friend! Firebug是你的朋友!

you can use jQuery ajax to make get or post request from javascript. 你可以使用jQuery ajax从javascript getpost请求。

jQuery.ajax({
  url: "url to controller method", // it should be mapped in routes.rb in rails
  type: "GET",
  data: {field1 :value1, field2:value2}, // if you want to send some data.
  dataType: "json"
  success: function(data){
  // data will be the response object(json)
  }
});

response from rails will something similar to the below, you can modify as per your requirement. rails的响应类似于下面的内容,您可以根据自己的要求进行修改。

respond_to do |format|
  format.js { render :json => @json_data }
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM