1

我正在尝试将变量“response.data.uri”从我的 jQuery 获取到 rails 控制器,但它不起作用。我可以到达 rails 控制器,但变量不存在。

jQuery:

function responseCallbackHandler(response) {
   switch (response.status) {
     case 201:
         $.ajax({ url: '#{addbank_bankaccts_path}',
         type: 'POST',
         beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', '#{form_authenticity_token}')},
         dataType: "json",
         data: 'account_uri=' + response.data.uri
         success: function(response) {
           // successfully executed the controller method
           }
         });
         break;
     }
 }

路线.rb:

post "/bankaccts/new" => 'bankaccts#addbank' 

控制器:

class BankacctsController < ApplicationController

  def addbank
      @uri = (params['customer_uri'])
      @id = (params['id'])
      @auri = (params['account_uri'])
      # all equal nil ^
      redirect_to root_url
  end
4

2 回答 2

2

Ah, I know: In ruby, single quotes do not perform variable interpolation. So if you posted the jquery as it appears in the browser, the url for you ajax request would be:

'#{addbank_bankaccts_path}'

...which is gibberish--a browser does not understand ruby or rails. Url's in a browser must look like:

http://mysite.com/js/myjs.js
js/myjs.js

If your jquery is in a file whose name ends with .erb, then before sending the file to the browser rails will execute any ruby code in the file, but single quotes in ruby do not perform variable interpolation. Here is an example of that:

name = 'Dave'
str = '#{name} says hello.'
puts str

--output:--
#{name} says hello

But with double quotes:

name = 'Dave'
str = "#{name} says hello."
puts str

--output:--
Dave says hello.

I don't know if you are coming from a python background or not, where all quotes are equivalent; but in a lot of languages, including ruby, single and double quotes are not equivalent.

Your form_authenticity_token has the same problem:

beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', '#{form_authenticity_token}')},
于 2013-08-07T05:21:43.873 回答
0

尝试 -

数据:{account_uri:response.data.uri,'customer_uri':SOME_VALUE,'id':SOME_VALUE}

于 2013-08-07T11:38:37.787 回答