简体   繁体   English

Rails 5:使用HTML(而非javascript)响应AJAX调用

[英]Rails 5: Respond to AJAX call with HTML (instead of javascript)

(Rails version 5.1.2) (发布版本5.1.2)

I would like to respond to AJAX with HTML rather than javascript for much the same reasons as outlined in this stack overflow question. 我想使用HTML而不是JavaScript来响应AJAX,其原因与堆栈溢出问题中概述的原因大致相同。

However, I can't actually get it to work. 但是,我实际上无法使其工作。

I'm using form_for with remote: true to send the request via AJAX. 我使用带有remote: true form_for通过AJAX发送请求。 Note that I've also experimented with data: {type: :html} . 请注意,我还尝试了data: {type: :html}

My controller action has the line render layout: !request.xhr? 我的控制器动作具有线render layout: !request.xhr? and has an associated view. 并具有关联的视图。 It's this view that I want sent back to the client. 我要将此视图发送回客户端。

Yet the client-side code: 客户端代码:

$("form").on('ajax:success', (e, data, status, xhr) ->
  console.log xhr.responseText #using console.log data produces same result
)

Gives: 得到:

Turbolinks.clearCache()
Turbolinks.visit("http://localhost:3000/...", {"action":"replace"})

Where's the HTML? HTML在哪里?

Unless I am completely misunderstanding what you want to do, this should be what you are looking for: 除非我完全误解了您想做什么,否则应该就是您要寻找的东西:

Javascript : Javascript

$.ajax({
  // remember to add this route to your routes file
  url: "products/ajax_render",
  success: function(data){
    $('.some_div').html(data['html'])
  },
});

Ruby on Rails : Ruby on Rails

def ajax_render
  # render some view and store it in a variable
  html = render "products/your_view"

  # return it inside the json response
  render json: { html: html }
end

Am I missing something? 我想念什么吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM