如何使用 AJAX 请求将 class 变量中用户的 HTML5 位置从 JavaScript 传递到 Rails 控制器?

How to use AJAX request to pass user's HTML5 location in a class variable from JavaScript to Rails controller?

我正在使用 Ruby (2.7.2p137),Ruby Rails (v6.0.3.4) 和 Geokit-rails (2.3.2 ).

我正在尝试将用户的位置传递到 Geokit-rails gem 的方法中。为此,我尝试使用 AJAX 请求将用户的 HTML5 位置从 JavaScript 传递到 Rails 控制器。

更新: Class 需要变量而不是实例变量来执行此操作。这在答案中有解释。

下面是调用show_location方法时来自服务器的error/response:

Started GET "/show_location?user_location%5B%7B%3Avalue%3D%3Enil%7D%5D=" for ::1 at 2021-02-21 13:03:18 +0000
Processing by PropertiesController#show_location as HTML
  Parameters: {"user_location"=>{"{:value=>nil}"=>""}}
Completed 500 Internal Server Error in 2ms (ActiveRecord: 0.0ms | Allocations: 1235)  
  
NoMethodError (undefined method `*' for nil:NilClass):

app/controllers/properties_controller.rb:77:in `show_location'

服务器上显示以下响应,因此 index.js 中的 JavaScript 似乎在工作:

Started POST "/user_long" for ::1 at 2021-02-21 12:57:13 +0000
Started POST "/user_lat" for ::1 at 2021-02-21 12:57:13 +0000
Processing by PropertiesController#user_lat as */*
  Parameters: {"lat"=>"53.3200896"}
No template found for PropertiesController#user_lat, rendering head :no_content
Completed 204 No Content in 80ms (ActiveRecord: 0.0ms | Allocations: 2885)


Processing by PropertiesController#user_long as */*
  Parameters: {"long"=>"-6.2521344"}
No template found for PropertiesController#user_long, rendering head :no_content
Completed 204 No Content in 34ms (ActiveRecord: 0.0ms | Allocations: 2340)

这是记录到浏览器控制台的 HTML5 位置对象:

Object
latitude: 53.3200896
longitude: -6.2521344
__proto__: Object

下面是我的 index.js 文件中请求 HTML5 位置的 JavaScript:

//function that gets the location and returns it
function getLocation() {
  if(navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else {
    console.log("Geo Location not supported by browser");
  }
}

//function that retrieves the position
function showPosition(position) {
  var location = {
    latitude: position.coords.latitude,
    longitude: position.coords.longitude
  }

  $(document).ready(function() {
    var lat = $(this).val();
    $.ajax({
        type: 'post',
        url: '/user_lat',
        data: {lat: position.coords.latitude},
    success: function(data) {
      console.log(data);
    }
    });      
  })

  $(document).ready(function() {
    var long = $(this).val();
    $.ajax({
        type: 'post',
        url: '/user_long',
        data: {long: position.coords.longitude},
    success: function(data) {
      console.log(data);
    }
    });      
  })

  console.log(location)
}

//request for location
getLocation();

这是我的 Rails 控制器 (properties_controller.rb) 中的方法,它根据指定坐标按距离显示属性列表:

def show_location

    @user_lat = user_lat

    @user_long = user_long

    @properties = Property.by_distance(:origin => [@user_lat, @user_long])

end

以下是我的属性控制器中用于 AJAX 请求的方法:

  def user_lat
    @user_lat = params["lat"]
  end

  def user_long
    @user_long = params["long"]
  end

我知道 gem 和控制器正在工作,因为当我将坐标硬编码到 show_location 方法中时,它可以成功工作。工作方法如下。

  def show_location
    
    @properties = Property.by_distance(:origin => [53.3200896,-6.2521344])

  end

所以我只需要帮助将用户的位置传递到此方法中。

使用上面的代码,我收到以下错误:

undefined method `*' for nil:NilClass

相关线路:

@properties = Property.by_distance(:origin => [@user_lat, @user_long])

感谢任何帮助。

我想通了。 AJAX 请求有效,但是 properties_controller 中的方法将用户的纬度和经度存储到实例变量而不是 class 变量。

实例变量不能used/accessed在方法外而class变量可以used/accessed在class.[=12=内的任何方法中]

下面 properties_controller.rb 更正了这一点:

  def user_lat
    @@user_lat = params["lat"]
    session[:user_lat] = @@user_lat
  end

  def user_long
    @@user_long = params["long"]
    session[:user_long] = @@user_long
  end

然后class变量被传递给show_location方法。

def show_location
    @properties = Property.by_distance(:origin => [@@user_lat, @@user_long])
end