2012-10-31 61 views
0

AutoComplete Railscast的评论部分中有一个问题没有答案,我需要同一个问题的帮助。 http://railscasts.com/episodes/102-auto-complete-association-revised?view=comments#comment_159833jQuery-UI Autocomplete Widget将多个参数传递给Rails服务器端数据源

我使用来自Rails控制器的数据源实现了jQuery-UI自动完成,而Rails控制器又调用了Foursquare API。 Foursquare API需要2个参数(一个“查询”和一个“lat/long”值)。

它发送给Rails控制器的Autocomplete小部件的默认参数是params [:term],其中包含“query”。我需要Autocomplete Widget从另一个text_field(我们称之为geocode_location字段)中提取值,并将其作为“latlong”参数传递。

所以有效的GET请求到Rails的控制器将

请求URL:http://localhost:3000/foursquare?ll=37.7+-122.5&term=McDonalds

,而不是

请求网址:网址:http://localhost:3000/foursquare?term=McDonalds

下面是我当前的CoffeeScript文件。我需要尝试通过extraParams或某种方式让它知道传递一个名为latlong的参数。我如何用Coffeescript和这种类型的数据源来做到这一点?

$('[type="text"][name*="[location]"]').autocomplete 
    source: $('[type="text"][name*="[location]"]').data('autocomplete-source') 
    focus: (event, ui) -> 
     event.preventDefault() 
     $(this).val ui.item.label 
    select: (event, ui) -> 
     event.preventDefault() 
     $(this).val ui.item.label 
     $(this).siblings('[name*="[foursquare_id]"]').val ui.item.value 

我对Coffeescript语法不是很熟悉,但真的很感谢这里的帮助。 这里有一个类似的问题,但自动完成结果的数据源是不同的。 jQuery UI - Autocomplete with extra params - returned data

+0

我对coffeescript不太熟悉,但我可以提供纯JS解决方案。这会有帮助吗? –

+0

是的,这将是伟大的。在这一点上 - 我认为任何正确的方向都会有所帮助。我会尽我所能翻译回Coffeescript并发回,如果它有效。谢谢@AndrewWhitaker –

回答

1

终于在很多很多小时后得到它。请参阅下面的关于如何应用附加参数传递给服务器端Rails控制器的语法。如此有效,我现在可以得到这个请求URL:http:// localhost:3000/foursquare?ll = 37.7 + -122.5 & term = McDonalds。希望这有助于某人。

$('[type="text"][name*="[location]"]').autocomplete(
    source: (request, response) -> 
     $.ajax 
     url: $('[type="text"][name*="[location]"]').data('autocomplete-source') 
     data: {term: request.term, ll: this.element.siblings('[name*="[geocode_location]"]').val()} 
     contentType: "application/json; charset=utf-8" 
     success: (data) -> 
      response $.map(data, (item) -> 
      value: item.value 
      label: item.label 
      address: item.address 
     ) 

    focus: (event, ui) -> 
     event.preventDefault() 
     $(this).val ui.item.label 
    select: (event, ui) -> 
     event.preventDefault() 
     $(this).val ui.item.label 
     $(this).siblings('[name*="[foursquare_id]"]').val ui.item.value 
).data("autocomplete")._renderItem = (ul, item) -> 
    $("<li>").data("item.autocomplete", item).append("<a>" + item.label + "<br>" + item.address + "</a>").appendTo ul