在ajax调用期间如何从Rails控制器方法返回值? [英] How to return value from a Rails controller method during an ajax call?
问题描述
<%= form_for(@mymodel, remote: true, html: { id: 'match_form' }) do |f| %>
<!-- I need to check if @mymodel.match_id matches the value generated by a controller function -->
<%= f.submit 'Save', class: 'btn btn-primary', id: 'match_submit', style: "width:38px;padding:0px" %>
<%= button_tag 'Cancel', class: 'btn btn-secondary', id: 'match_cancel', style: "width:52px;padding:0px" %>
<% end%>
<script type='text/javascript'>
$(function() {
$(document).on("click", "#match_submit", function(event){
$.ajax('my_controller_method', {
type: 'GET',
dataType: 'script',
data: {
mid: $("#").val(), // how do I pass @mymodel.match_id here?
},
error: function(jqXHR, textStatus, errorThrown) {
return console.log("AJAX Error: " + textStatus);
}
});
});
</script>
我有上面的JavaScrpt代码,可以对Rails控制器方法进行ajax调用.
I have the above JavaScrpt code which makes an ajax call to a Rails controller method.
我想检查在此ajax调用中传递的值是否与某个值匹配.如果没有,我想只用 Ok
按钮显示模式错误消息.
I would like to check if the value passed in this ajax call matches a certain value. If not, I would like to display a modal error message with only an Ok
button.
我可以想到两种方法来实现这一目标:
I can think of 2 ways to achieve this:
-
我可以从控制器方法中返回正确的值(这需要通过运行SQL查询进行一些计算.这就是为什么我在控制器方法中进行此操作)并检查JavaScript中的相等性,并在出现以下情况时抛出JavaScipt警报没有匹配项.
I can return the correct value from the controller method (this requires some calculation by running a SQL query. That's why I am doing this in a controller method) and check the equality in JavaScript and throw a JavaScipt alert if there is no match.
问:为此,我想知道如何从控制器函数(在ajax调用期间调用)将数字返回给JavaScript
Q: For this I would like to know how I can return a number from a controller function (called during ajax call) back to the JavaScript
我可以检查控制器本身内部的匹配项,然后在控制器函数本身中呈现引导程序模式
I could check for the match inside the controller itself and then render a bootstrap modal in the controller function itself
问:为此,我想知道如何在我的控制器函数中呈现一个引导程序模态(它显示一条文本消息,并且只显示一个 Ok
按钮".
Q: For this I would like to know how to render a bootstrap modal (which shows a text message and only an Ok
button) inside my controller function.
推荐答案
def my_controller_method
# assign your value here like,
@message = 'Error occured!'
end
将js文件另存为
my_controller_method.js.erb
my_controller_method.js.erb
在此js文件中,
$("#mymodaldiv").html("<%= j render(partial: 'my_partial_page',locals: {msg: @message}) %>");
在这里,mymodaldiv是您必须在发生AJAX调用的文件中放入div的ID,
Here, mymodaldiv is the id of the div that you have to put in your file from where AJAX call is happening as,
<div id='mymodaldiv'></div>
和my_partial_page是您必须使用msg变量构造页面的部分的名称.
and my_partial_page is the name of your partial where you have to use msg variable to construct your page. as,
_my_partial_page.html.erb
_my_partial_page.html.erb
和文件_my_partial_page.html.erb中的代码类似,
and code in the file _my_partial_page.html.erb goes like,
<h1><%= msg %></h1>
这篇关于在ajax调用期间如何从Rails控制器方法返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!