简体   繁体   English

将jQuery变量发送到Rails控制器

[英]Sending a jQuery variable to Rails controller

I'm trying to get the variable "response.data.uri" from my jQuery to a rails controller, but it isn't working. 我正在尝试从我的jQuery到Rails控制器获取变量“ response.data.uri”,但是它不起作用。 I can get to the rails controller but the variable isnt there. 我可以去到rails控制器,但是那里没有变量。

jQuery: 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;
     }
 }

routes.rb: routes.rb中:

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

controller: 控制器:

class BankacctsController < ApplicationController

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

Ah, I know: In ruby, single quotes do not perform variable interpolation. 啊,我知道:在ruby中,单引号不执行变量插值。 So if you posted the jquery as it appears in the browser, the url for you ajax request would be: 因此,如果您发布的jquery出现在浏览器中,那么您的ajax请求的网址将是:

'#{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. 如果您的jquery在名称以.erb结尾的文件中,则在将文件发送到浏览器之前,rails将执行文件中的所有ruby代码,但是ruby中的单引号不会执行变量插值。 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; 我不知道您是否来自python背景,所有引号都相等; but in a lot of languages, including ruby, single and double quotes are not equivalent. 但是在包括红宝石在内的许多语言中,单引号和双引号都不等效。

Your form_authenticity_token has the same problem: 您的form_authenticity_token存在相同的问题:

beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', '#{form_authenticity_token}')},

Try - 尝试-

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM