ruby-on-rails - 从 Rails 助手或控制器调用刺激控制器中的函数?
问题描述
我正在开发一个 Rails 应用程序,我想在其中使用 Javascript 的导航 API 来获取用户的地理位置。我在“app/javascript/location_controller”下的控制器中有代码,它可以工作。
import { Controller } from "stimulus"
export default class extends Controller {
connect(){
this.getUserLocation()
}
getUserLocation(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => console.log(position.coords), (error)=> console.log(error));
} else {
alert("Could not get your current location! Please allow location services for RiseUp.")
}
}
}
我将如何从 Rails Helper 调用“getUserLocation”?
解决方案
Stimulus 控制器,通常是任何 javascript,不是由您的 ruby 服务器运行,而是由用户的浏览器运行。
如果您想从中获取值,则需要进行一些 ajax 调用,并从普通的 rails 控制器中获取。
就像是:
async getUserLocation() {
let data = new FormData();
let position = await navigator.geolocation.getCurrentPosition();
data.set('position', position);
await fetch('/api/notify_location', {method: 'POST', body: data, credentials: true});
}
你必须在后端路由它:
scope 'api' do
post 'notify_location' => 'location#notify'
end
并将其放入控制器中
class LocationController < ApplicationController
def notify
# do as needed, you will be able to get the session here
# because the fetch function was passed credentials: true
# but beware, this request won't match `request.xhr?` because
# fetch is not XMLHTTPRequest.
推荐阅读
- python - Pycharm 中的运行和待办事项选项卡
- powershell - 如何将变量扩展为几个空格分隔的程序参数
- php - 如何在 php 中使用 curl 从网页中获取特定内容?
- javascript - 使用嵌套对象对数组内的值进行分组和计数
- html - 使用 vba 错误 438 抓取网页让我发疯
- java - 带有日期和运算符的 SQL 查询 Springboot
- javascript - JavaScript中基于字符串+数值对对象数组进行排序
- windows - kotlin 代码的运行时编译抛出 RuntimeException(警告:无法为 Windows 初始化本机文件系统)
- python - Visual Studio(python)中的异常未处理错误
- python - 如何将 paramiko 与 pexpect 一起使用?