stackoverflow 中的所有其他解决方案似乎都不适合我,因此我发布我的代码以寻求帮助。我想通过jquery输出变量:@less_per_unit
这是我在 _form.html.erb 中的标签:
<script>
$(document).on('keyup', ".input-quantity", function(){
$.ajax({
url: "/so_check_increment",
type: "GET",
data: { quantity: $(this).val(), product_id: $(this).closest('tr').find('.input-product_code').val()}
});
$(this).closest('td').next('td').find('.increment').text('<%== j @less_per_unit%>');
});
</script>
这是我的 Controller :
def check_increment
@less_per_unit = "testing"
end
我知道ajax可以工作,我也设置了路线。如果我尝试绑定(bind).pry,我知道rails可以找到@less_per_unit,但我无法用javascript输出它。
最佳答案
这不起作用,因为:
假设此表单是在 Controller “Post”的“new”操作中呈现的,那么需要在那里初始化@less_per_unit
,以便在您正在使用的该操作的 View 文件中使用它。当您使用 AJAX 调用并在该调用期间时,您正在定义一个实例变量,该变量肯定无法被已渲染的 html 文件访问。
因此,您需要从 check_increment 操作返回 JSON 数据,并在 AJAX 调用响应中接收该数据,然后使用它。
关于javascript - 无法访问 Javascript 标记内的 Rails 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47252580/