0

I'm trying to query our database on the .click function. I can alert(val) so that's working. But I'm trying to figure out how to go to the database and find out if a record in Discount table exists where Discount.amount == val

  $(document).ready ->
  $("button.discount").click ->
    val = $('input.discount').val()
    store = window.location.pathname.split('/')[1]

// Would like to do something like this, I'm guessing with ajax:

d = Discount.find_by_name(val)
if d
  return d.amount
else
  return "No discount exists"
end
4

1 回答 1

0

只需使用 jQuery$.get()方法:

$(document).ready ->
  $("button.discount").on "click", (event) ->
    val = $(this).val()

    $.get 'domain/discount/?discount_value=' + val # Send the discount value as parameter
      (data) ->
        switch data
          when 'ok' then do something ...
          when 'ko' then do another thing ...

在你的 Rails 控制器中(假设到你的控制器的路由看起来像这样domain/discount/?discount_value=X:)

d = Discount.find_by_name(params['discount_value'])
if d
  response = d.amount
  status = "ok"
else
  status = "ko"

respond_to do |format|
  msg = { :status => status, :amount => response }
  format.json  { render :json => msg }
end
于 2013-05-07T15:31:12.573 回答