使用从AJAX请求接收的params设置表单值



我目前正在设计一个应用程序,用户需要添加一个商店,该商店可以获取他们的位置并自动填充新商店表单的纬度和经度字段。到目前为止,我已经能够设置地理位置脚本,并通过AJAX调用将参数发送到我的rails控制器,但就我的一生而言,我无法获得自动设置这些值的表格。

在我的rails服务器日志中,它显示了经度和纬度的参数正在被传递。

根据我所读到的内容,这些应该可以作为params[:纬度]和params[:经度]使用,但如果我将表单值设置为这些,则不会发生任何事情。

我的服务器日志显示参数已传递:

Processing by StoresController#new as */*
Parameters: {"latitude"=>"-29.13184", "longitude"=>"26.195021399999998"}
User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?  [["id", 1], ["LIMIT", 1]]
Rendering stores/new.html.erb within layouts/application
Rendered layouts/_messages.html.erb (0.5ms)
Rendered stores/_form.html.erb (6.0ms)
Rendered stores/new.html.erb within layouts/application (10.1ms)
Completed 200 OK in 38ms (Views: 31.3ms | ActiveRecord: 0.2ms)

我的Rails控制器具有新的和创建的操作:

class StoresController < ApplicationController
def new
@store = current_user.stores.build
end
def create
@store = current_user.stores.build(store_params)
if @store.save
flash[:success] = "New store was successfully saved"
redirect_to @store
else
flash[:danger] = "There was an error in adding new store"
render 'stores/new'
end
end

我的地理定位脚本:

<script>
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(sendLocation);
} else {
alert("Geolocation is not supported by this browser.");
}
function sendLocation(position){
var latitude  = position.coords.latitude;
var longitude = position.coords.longitude;
jQuery.ajax({
data: { latitude: latitude, longitude: longitude},
type: 'get',
url: "/stores/new",
});
};
</script>

我的表单部分:

<%= form_for(@store) do |f| %>
<%= f.text_field :storename, class: 'form-control',
placeholder: "Store Name", autofocus: true %>
</br>
<%= f.text_field :storecode, class: 'form-control', placeholder: "Store Code" %>
</br>
<%= f.text_field :contactname, class: 'form-control', placeholder: "Store Contact" %>
</br>
<%= f.telephone_field :phonenumber, class: 'form-control', placeholder: "Contact Number" %>
</br>
<%= f.text_field :latitude, :value => params[:latitude] %>
</br>
<%= f.text_field :longitude, :value => params[:longitude] %>
</br>
<div class="span1">
<p><%= f.submit "Submit", class: "btn btn-warning btn-block" %></p>
<p><%= link_to "Back", dashboard_path, class: "btn btn-warning btn-block" %></p>
</div>
<% end %>
</br>
<%= render '/layouts/messages' %>

我希望表单中的:latitude和:经度的text_fields自动接收通过AJAX传递给控制器的:纬度和:经度值。基本上,我希望用户能够站在商店里,将他/她的经度和纬度传递给控制器,以便自动插入表单,这样用户就不需要手动添加坐标。

如果我的问题不清楚,我深表歉意。经过更多的研究,我设法解决了这个问题。

我只是在纬度和经度字段中添加了一个id,并将脚本更改为以下内容。

if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(sendLocation);
} else {
alert("Geolocation is not supported by this browser.");
}
function sendLocation(position){
var latitude = position.coords.latitude;
longitude = position.coords.longitude;
document.getElementById('latitude').value = latitude;
document.getElementById('longitude').value = longitude;
}

表单现在在找到位置后填充纬度和经度字段。

最新更新