0

ポイントを送信するためのajaxフォームがあり、これらのポイントを使用して、これら2つのポイント間の最短パスを見つけます。

これはすべてajaxなしで機能します。データをサーバーに送信してページを再レンダリングするだけですが、ajaxでこの作業が必要です

問題は、サーバー(コントローラー+モデル)で生成したデータ(json)をクライアント(ビュー)に送信/アップロードできないことです

私はこれをやっています(1)、それがajaxなしで機能すると言った方法

(1)

# views/places/finder.html.erb    
<%= form_tag({controller: "places", action: "found"}, remote: true) do %>
    <%= hidden_field_tag :lon_s %> # 
    <%= hidden_field_tag :lat_s %> # these fields are updated automatically
    <%= hidden_field_tag :lon_t %> # with clicks the user do on the map 
    <%= hidden_field_tag :lat_t %> #

    <%= submit_tag "Buscar ruta", id: 'buscar_ruta' %>
<% end -%>

#places_controller.rb
def found
    res = Way.path_cost_from(params[:lon_s].to_f, params[:lat_s].to_f, 
                             params[:lon_t].to_f, params[:lat_t].to_f)
    @costo = res[:cost]
    gon.poly = Way.get_way(res[:edges])
    @path = Way.get_way(res[:edges])
end

#views/places/found.js.coffee
console.log <%= @costo %> #this show the cost in the console, it works.
console.log <%= gon.poly %> #undefined local variable or method `gon'
console.log <%= @path %> #Error: Parse error on line 3: Unexpected ':'

ajax を使用しないバージョンの前に、gon gemを使用して、Google マップ API に必要なポイントを渡し、ポリラインを表示/構築する必要がありました。

#assets/javascripsts/places.js.coffee
if gon.poly?
  poly = gon.poly
  MAP.addPolyline poly

polyは、json 形式で作成したオブジェクトです。

each do |point|
    path << { lon: unprojected_point.x, lat: unprojected_point.y }
end
return path

必要に応じて、私のプロジェクトを私の github アカウントhttps://github.com/figuedmundo/finalで見ることができます。

これを行う例を探していましたが、見つかった唯一の例は、ページを更新するためのいくつかの html コード (通常の ajax) をレンダリングすることでしたが、Google マップ API は単なる JavaScript です。


解決

私のコードのアイデアは最適ではないかもしれませんが、それは機能し、最終的にクライアントが望んでいることです.

問題は、ビューに自動的に渡された変数@pathがエスケープされたため、json オブジェクトが読み取れないことでした。html_safeはトリックを行います

console.log <%=  @path.html_safe %>
4

1 に答える 1

0

<%= submit_tag "Buscar ruta", id: 'buscar_ruta' % の代わりに <%= f.submit_tag "Buscar ruta", id: 'buscar_ruta' %> を使用してみてください。

于 2012-09-26T00:11:53.637 に答える