[英]Using Ajax to GET data from Rails controller
I am trying to get an instance of a modal (in JSON format) by using Ajax when a form is submitted. 我正在尝试在提交表单时使用Ajax获取模态(JSON格式)的实例。 Currently, on the alert, it outputs nothing, blank.
当前,在警报中,它什么也不输出,为空白。
alert('<%= @modal_data.to_json.html_safe %>');
outputs JSON data, but alert(data);
输出JSON数据,但
alert(data);
called through Ajax does not output anything. 通过Ajax调用不会输出任何内容。
Controller 控制者
class ModalController < ApplicationController
def modal_index
@modal_data = Modal.where(:var => params[:attr1])
respond_to do |format|
format.html
format.json {render json: @modal_data}
end
end
end
JavaScript 的JavaScript
$(document).ready(function() {
$('#my_form').on("submit", function () {
$.ajax({
type: "GET",
dataType: "json",
url: "/modal/modal_index",
success: function(data){
alert(data);
}
});
});
});
In order for this to work with JSON you need to set the content type to application/json
. 为了使它与JSON一起使用,您需要将内容类型设置为
application/json
。
if your $.ajax
call 如果您的
$.ajax
电话
$(document).ready(function() {
$('#my_form').on("submit", function () {
$.ajax({
type: "GET",
contentType: "application/json",
url: "/modal/modal_index",
success: function(data){
alert(data);
}
});
});
});
Also, it doesn't seem you provided the param needed to find the model (attr1). 另外,似乎您没有提供找到模型(attr1)所需的参数。
Keep your controllers standard, pass id
or item_id
to get in order to get the object you need. 保持您的控制器标准,传递
id
或item_id
以获得以获得所需的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.