Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何在RubyonRails中设置Ajax调用中的区域设置?_Ruby On Rails_Ruby_Ruby On Rails 3_Jquery_Ruby On Rails 3.2 - Fatal编程技术网

Ruby on rails 如何在RubyonRails中设置Ajax调用中的区域设置?

Ruby on rails 如何在RubyonRails中设置Ajax调用中的区域设置?,ruby-on-rails,ruby,ruby-on-rails-3,jquery,ruby-on-rails-3.2,Ruby On Rails,Ruby,Ruby On Rails 3,Jquery,Ruby On Rails 3.2,我在application.js文件中有这个Ajax函数: $("#project_person_id").change(function() { $.ajax({ url: '/projects/get_invoice_types', data: 'person_id=' + this.value, dataType: 'script' }) }); 是否可以在该函数中使用区域设置 当我将第3行更改为: url: '/de/pr

我在
application.js
文件中有这个Ajax函数:

$("#project_person_id").change(function() {
    $.ajax({
        url: '/projects/get_invoice_types',
        data: 'person_id=' + this.value,
        dataType: 'script'
    })
});
是否可以在该函数中使用区域设置

当我将第3行更改为:

url: '/de/projects/get_invoice_types',
我得到了期望的结果(即德语输出)

当然,我想动态地设置它。如何做到这一点


谢谢您的帮助。

您可以在任何地方动态设置它,即

var locale = "de"; // set it dynamically
然后把它当作一个全局的,像这样

$("#project_person_id").change(function() {
    $.ajax({
        url: "/"+locale+'/projects/get_invoice_types', // use it
        data: 'person_id=' + this.value,
        dataType: 'script'
    })
});
更优雅的做法是将其设置为body标记
或HTML头
的数据属性,并使用函数将其拉入

function locale(){return$(“body”).data(“locale”)}
function locale(){return$(“html”).attr(“lang”)}
然后按如下方式检索它:

$("#project_person_id").change(function() {
    $.ajax({
        url: "/"+locale()+'/projects/get_invoice_types', // use it
        data: 'person_id=' + this.value,
        dataType: 'script'
    })
});

当然,还有其他选择,这些选择似乎很简单

我通过修改$.get和$.post jQuery函数解决了这个问题

在我的例子中,locale是url中的一个参数,但它也可以像Sagish那样被注入

当我调用$.get或$.post时,区域设置会自动添加到URL:

...   
var remote_search=$.get("/expenses/search_users/"+$(this).val());

    remote_search(function( data ) {
          $("#processing").hide();
          alert( "Usuari inexistent");
          obj_error.val("");
});
...

我通过向erb模板添加数据属性解决了这个问题

<button type="button" class="btn btn-success" id="save-job-position-btn" data-locale="<%= params[:locale] %>"><%= t("save") %></button>
<button type="button" class="btn btn-success" id="save-job-position-btn" data-locale="<%= params[:locale] %>"><%= t("save") %></button>
$( "#save-job-position-btn" ).click(function() {
  var locale = $(this).data("locale");
}