简体   繁体   English

将JavaScript变量传递给Rails控制器上的ruby以进一步发送api

[英]pass javascript variable to ruby on rails controller to send in api further

I am having a google api map as index.html 我将Google api地图作为index.html

<!DOCTYPE html>
<html>
<head>

<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
  html, body {
    height: 100%;
    margin: 0;
    padding: 0;
  }
  #map {
    height: 100%;
  }
</style>
</head>
<body>
<div id="map"></div>
<script>
  // Note: This example requires that you consent to location sharing when
  // prompted by your browser. If you see the error "The Geolocation service
  // failed.", it means you probably did not give permission for the browser to
  // locate you.

  function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
      center: {lat: -34.397, lng: 150.644},
      zoom: 15
    });
    var infoWindow = new google.maps.InfoWindow({map: map});

    // Try HTML5 geolocation.
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        var pos = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };

        infoWindow.setPosition(pos);
        infoWindow.setContent('Location found.');
        map.setCenter(pos);
      }, function() {
        handleLocationError(true, infoWindow, map.getCenter());
      });
    } else {
      // Browser doesn't support Geolocation
      handleLocationError(false, infoWindow, map.getCenter());
    }
  }

  function handleLocationError(browserHasGeolocation, infoWindow, pos) {
    infoWindow.setPosition(pos);
    infoWindow.setContent(browserHasGeolocation ?
                          'Error: The Geolocation service failed.' :
                          'Error: Your browser doesn\'t support geolocation.');
  }



    </script>
    <script async defer
src="https://maps.googleapis.com/maps/api   /js?key=AIzaSyBNvjq57_K8vPYRKETMN6bDogqCpRvBoA0&callback=initMap">
    </script>
    </body>
    </html>

I want to use the var=pos in ruby on rails controller ie products controller 我想在Rails控制器即产品控制器中使用var = pos在ruby中

require 'rubygems'

    require 'httparty'

    class ProductsController < ApplicationController



def index

    @results = HTTParty.get("https://api.uber.com          /v1/products?server_token=xyz&latitude=37.7759792&longitude=-122.41823").parsed_response

   respond_to do |format|
   format.json { render :json => JSON.parse(@results) }
   format.html { render "index.html.erb" }
   end
   end
   end

and then pass seperate latitude and longitude in the api url so that it can take any latitude and longitude instead of giving it manually. 然后在api网址中传递单独的纬度和经度,以便它可以接受任何纬度和经度,而无需手动指定。 How can I do it ? 我该怎么做 ? Any suggestion would be appreciated. 任何建议,将不胜感激。

As @max said, you have to make another request to a controller. 正如@max所说,您必须向控制器提出另一个请求。 If you use jQuery and want to make an AJAX request, it can be done like so: 如果您使用jQuery并想发出AJAX请求,则可以这样进行:

$.ajax({
  method: "GET",
  url: "products/some_action",
  data: { lat: pos.lat, lng: pos.lng }
})
.done(function( msg ) {
  alert( "Done" );
});

see http://api.jquery.com/jquery.ajax/ 参见http://api.jquery.com/jquery.ajax/

and in your ProductsController add: 并在您的ProductsController添加:

def some_action
  # do something with params[:lat] and params[:lng]
end

solved the problem asked above by passing params in windows.open javascript function and fetching that params in products controller 通过在windows.open javascript函数中传递参数并在产品控制器中获取该参数,解决了上述问题

index.html: index.html的:

<!DOCTYPE html>
<html>
<head>

<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
  html, body {
    height: 100%;
    margin: 0;
    padding: 0;
  }
  #map {
    height: 100%;
  }
</style>
</head>
<body>
<div id="map"></div>
<script>
  // Note: This example requires that you consent to location sharing when
  // prompted by your browser. If you see the error "The Geolocation service
  // failed.", it means you probably did not give permission for the browser to
  // locate you.

  function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
      center: {lat: -34.397, lng: 150.644},
      zoom: 15
    });
    var infoWindow = new google.maps.InfoWindow({map: map});

    // Try HTML5 geolocation.
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        var pos = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };

        infoWindow.setPosition(pos);
        infoWindow.setContent('Location found.');
        map.setCenter(pos);
          if(pos){
          window.open("/products?lat="+pos.lat+"&long="+pos.lng,"_blank")
        }
      }, function() {
        handleLocationError(true, infoWindow, map.getCenter());
      });
    } else {
      // Browser doesn't support Geolocation
      handleLocationError(false, infoWindow, map.getCenter());
    }
  }

  function handleLocationError(browserHasGeolocation, infoWindow, pos) {
    infoWindow.setPosition(pos);
    infoWindow.setContent(browserHasGeolocation ?
                          'Error: The Geolocation service failed.' :
                          'Error: Your browser doesn\'t support geolocation.');
  }



    </script>
    <script async defer
src="https://maps.googleapis.com/maps/api   /js?key=AIzaSyBNvjq57_K8vPYRKETMN6bDogqCpRvBoA0&callback=initMap">
    </script>
    </body>
    </html>

products controller: 产品负责人:

require 'rubygems'

    require 'httparty'

    class ProductsController < ApplicationController



def index
    lat = params[:lat].to_s
    long = params[:long].to_s
    @results = HTTParty.get("https://api.uber.com/v1/products?server_token=your_server_token&latitude="+lat+"&longitude="+long).parsed_response


   respond_to do |format|
   format.json { render :json => JSON.parse(@results) }
   format.html { render "index.html.erb" }
   end
   end
   end

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

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