从AJAX传递变量到控制器操作时缺少模板

时间:2015-01-09 16:35:35

标签: ruby-on-rails

我想将一个变量从AJAX(JS文件)传递给controller#action。但它没有通过并返回“缺少模板”的错误。我该如何解决这个问题?

我的AJAX代码:

function message_for(username){
  $.ajax({
    url: '/show_message',
    method: 'POST',
    data: {
        to: username
    },
    success: function(response){
        alert(response);
    }
  })
}

Def show_message:

def show_message
    @to = params[:to]
    Message.all_messages(@to)
end

路线:

post '/show_message' => 'messages#show_message'

但它不起作用。 错误日志打印:

Started POST "/show_message" for 194.135.153.182 at 2015-01-09 09:37:45 -0500
Processing by MessagesController#show_message as */*
Parameters: {"to"=>"alizade"}
Completed 500  in 13ms

ActionView::MissingTemplate (Missing template messages/show_message, application/show_message with {:locale=>[:en], :formats=>[:html, :text, :js, :css, :ics, :csv, :vcf, :png, :jpeg, :gif, :bmp, :tiff, :mpeg, :xml, :rss, :atom, :yaml, :multipart_form, :url_encoded_form, :json, :pdf, :zip], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}. Searched in:
  * "/usr/local/projects/bookworm/app/views"
):

1 个答案:

答案 0 :(得分:2)

你真的需要更换' POST'与' GET'请求(省略method属性,默认情况下你有)。您还需要使用render plain

以下是控制器操作的示例实现:

def show
  text_to_alert = 'Hello There'
  render plain: text_to_alert
end

现在使用您要提醒的任何文字内容填写text_to_alert

你的ajax电话应该​​是这样的:

var url = '/messages/show';
var username = 'foo_username';
var data = {
  to: username
};
$.ajax({
        url: url,
        data: data,
        success: function(data, textStatus, jqXHR) {
            alert(data);
        }
});

这是一个指示性实施,但你明白了。

我已经实现了一个示例Rails项目,该项目演示了上述内容并且可以正常运行。这是:ajax_get_request_example