<%= 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>
我有一个如上所示的表格。
- 如何在上面的 ajax 调用中传递 @mymodel.match_id?
- 在我的 Controller 函数中,我想检查传递的 match_id 是否是某个值;如果没有,我想显示一个带有错误消息的模式和一个
Ok
按钮。我怎样才能实现这个目标?
< > a) 我应该从 Controller 函数返回正确的值并在上面的 javascript 代码中检查相同的值并显示 javascript 警报吗?
< > < > i) 如果是,那么如何将数字从 Controller 函数返回到我的 JavaScript 调用函数?
或
< > b) 我是否能够使用 Controller 本身中的Ok
按钮渲染引导模式?
更新 1:
我尝试将 match_id
和 id
从 mymodel
传递到 ajax 调用,但它不起作用:
$(document).on("click", "#match_submit", function(event){
alert ("match id changed!");
alert($("#match_form").data('id'));
alert($("#match_form").data('match_id'));
$.ajax('cpl_evaluate_match_id', {
type: 'GET',
dataType: 'script',
data: {
debit_id: $("#match_form").data('id'),
match_id: $("#match_form").data('match_id')
},
error: function(jqXHR, textStatus, errorThrown) {
return console.log("AJAX Error: " + textStatus);
}
});
});
在警报消息中打印 id
和 match_id
的警报打印 undefined
。
更新2:
我尝试从我的 Controller 函数返回一个数字,但这似乎也不起作用:
def evaluate_match_id
puts params[:debit_id]
puts params[:match_id]
return 1
end
上面的看跌期权变成空白
$(document).on("click", "#match_submit", function(event){
alert ("match id changed!");
alert($("#match_form").data('id'));
alert($("#match_form").data('match_id'));
$.ajax('cpl_evaluate_match_id', {
type: 'GET',
dataType: 'script',
data: {
debit_id: $("#match_form").data('id'),
match_id: $("#match_form").data('match_id')
},
success: function(result){
if(result){ // yes or no? 1 or 0, it's the return coming from your controller
alert('true');
alert(result);
}
else{
alert('error');
alert(result);
}
},
error: function(jqXHR, textStatus, errorThrown) {
return console.log("AJAX Error: " + textStatus);
}
});
});
上面 JavaScript 代码中 success:
block 中 result
的值显示为 undefined
(我的 Controller 函数盲目地返回数字1
我希望它是这里 result
的值)。因此 if(result)
条件失败,并且 else
block 被调用。
最佳答案
你可以使用attr来获取jquery中的value元素。像这样的东西
$('#match_form').attr('id')
关于javascript - 如何匹配 Rails Controller 中 ajax 调用发送的值并显示错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60164334/