簡體   English   中英

將Javascript變量保存到Ruby中

[英]Saving Javascript Variable Into Ruby

我正在使用HTML 5地理位置代碼( http://www.w3schools.com/html/html5_geolocation.asp )獲取用戶位置。

...
function showPosition(position)
  {
    x.innerHTML="Latitude: " + position.coords.latitude + 
    "<br>Longitude: " + position.coords.longitude; 
  }
</script>

我想在ruby中創建一個包含position.coords.latitude和position.coords.longitude的值的變量,有人知道捕獲此信息並將其另存為ruby變量的最有效方法嗎?

嗯,有兩種方法可以做到這一點-

  1. 撥打ajax電話

     var latitude = position.coords.latitude; var longitude = position.coords.latitude; $.ajax({ url: "/<some_route>?latitude="+latitude+"&longitude="+longitude, success: function(data) { // do something here like for example replace some arbitrary container's html with the stuff returned by server. $("#container").html(data); } }); 

    使用params hash在服務器端訪問它

     latitude = params[:latitude] longitude = params[:longitude] 
  2. 在客戶端設置位置cookie,並在服務器端訪問它。

     var latitude = position.coords.latitude; var longitude = position.coords.longitude; document.cookie = "cl=" + latitude + "&" + longitude + ";"; 

    在您的控制器中,您可以訪問-

     current_location = cookies[:cl] unless current_location.nil? latitude = current_location.split('&')[0] longitude = current_location.split('&')[1] end 

話雖這么說,您應該選擇選項1,因為cookie是隨每個HTTP請求發送到服務器的,另外,您可能需要通知用戶使用了跟蹤技術。

一個請求主要包括以下步驟:

  1. 瀏覽器向服務器請求頁面
  2. 服務器處理請求並返回頁面,該頁面可能包含Javascript代碼
  3. 瀏覽器執行javascript代碼並繼續進行處理

如何擁有僅在步驟2 3存在的變量的問題,這是不可能的。

一種替代方法是簡單地添加一個ajax調用(即,重復步驟1至3,而不是“ Browser”閱讀“ Javascript代碼”),該信息會將此信息發送到服務器以保存在數據庫中或其他內容中,但是您仍然可以在javascript中編寫邏輯程序。

有誰知道捕獲此信息並將其另存為紅寶石變量的最有效方法?

您的有效衡量標准是什么? 數據到達服務器時會不會丟失隨機數字嗎?

發出jQuery ajax請求是最簡單的

var lat = 10;
var lon = 20;

function onsuccess(data, textStatus, jqXHR) {  
    alert(textStatus); 
}

$.post(
    "http://localhost:3000/some/route",
    {'lat': lat, 'lon': lon},
    onsuccess   //optional
);

緯度和經度可以從params哈希中檢索到:

lat = params[:lat]
lon = params[:lon]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM