gpt4 book ai didi

javascript - 将 javascript 变量传递给 ruby​​ on rails Controller 以进一步发送 api

转载 作者:行者123 更新时间:2023-11-30 16:03:04 24 4
gpt4 key购买 nike

我有一个 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>

我想在 ruby​​ on rails Controller 中使用 var=pos,即产品 Controller

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

然后在 api url 中传递单独的纬度和经度,以便它可以采用任何纬度和经度,而不是手动提供。我该怎么做 ?任何建议将不胜感激。

最佳答案

正如@max 所说,您必须向 Controller 发出另一个请求。如果您使用 jQuery 并想发出 AJAX 请求,可以这样做:

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

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

并在您的 ProductsController 中添加:

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

关于javascript - 将 javascript 变量传递给 ruby​​ on rails Controller 以进一步发送 api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37411903/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com