开发者

Access posted json data from ajax in rails controller

I have made an ajax post request for json data and I want to access that data in the rails controller so how can I access the data.

Here is how I posted the data using ajax

jQuery.ajax({
          url: 'main/getlocation',
          data: "{latitude:" + latitude + ",longitude:" + longitude + "}",
    开发者_StackOverflow中文版      dataType: 'json',
          type: "POST",
          success: function(data) {
            alert("Successful");
          },
          failure: function() {
            alert("Unsuccessful");
          }
        }); 

How can I access the latitude and longitude data from the rails controller. I cannot access the data using the normal params[:latitude] and params[:longitude]. What should I use?


I guess you have assigned longitude and latitude as variables which is accessible by your ajax request. If its not you will not get anything in the controller. Make sure the variables scope is right , then try this :

jQuery.ajax({
          url: 'main/getlocation',
          data: "latitude=" + latitude + "&longitude=" + longitude,
          type: "POST",
          success: function(data) {
            alert("Successful");
          },
          failure: function() {
            alert("Unsuccessful");
          }
        }); 

Now, I guess you can get the params[:longitude] and params[:latitude] in your controller.


You dont need to define type json in your jquery ajax post request. use below code in your javascript

jQuery.ajax({
          url: 'main/getlocation',
          data: {latitude:latitude,longitude:longitude},
          type: "POST",
          success: function(data) {
            alert("Successful");
          },
          failure: function() {
            alert("Unsuccessful");
          }
        }); 

and now try

params[:latitude] and params[:longitude] in your controller.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜