0

AutoComplete Railscast 的评论部分有一个问题没有得到解答,我需要有关相同问题的帮助。 http://railscasts.com/episodes/102-auto-complete-association-revised?view=comments#comment_159833

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

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

如此有效,对 Rails 控制器的 GET 请求将是

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

并不是

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

以下是我当前的咖啡脚本文件。我需要尝试传递它 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 - 带有额外参数的自动完成 - 返回的数据

4

1 回答 1

2

经过很多很多小时终于得到它。有关如何应用附加参数以传递到服务器端 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
于 2012-11-01T21:54:15.597 回答