You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby on Rails文件读取内容通过Ajax展示格式异常求助

问题分析与解决方案

看起来你的核心问题是后端返回的文本格式被破坏,根源出在控制器的响应渲染方式上。咱们一步步拆解解决:

为什么格式会乱?

你当前用render text: {result: file_content}返回内容,这里有个关键问题:你把纯文本内容包裹在了Ruby哈希里,然后用render text输出。Rails会把这个哈希直接转换成字符串形式(比如变成"{:result=>'你的原文本内容...'}"),前端拿到的不是原始的纯文本,而是带哈希结构的字符串,自然原文件的换行、缩进这些格式就全乱了。

修正方案

根据你的需求,有两种合适的返回方式,选一种匹配你前端逻辑的即可:

方案1:直接返回纯文本(推荐,仅需展示文本内容时)

把控制器里的render text: {result: file_content}改成render plain: file_content,render plain会告诉Rails返回纯文本类型的响应,Content-Type设为text/plain,前端拿到的就是和原文件完全一致的内容。

修正后的控制器代码:

require "rinruby"
class MedicationsController < ApplicationController
  def ndc_crawl
    ndc = NDCCode.find_by(ndc_code: params[:ndc])
    ndc.crawl
    file_content = File.read("#{Rails.root}/product_info.txt")
    puts file_content
    # 返回纯文本,保留原格式
    render plain: file_content
  end
end

前端Ajax处理(以jQuery为例):

$.ajax({
  url: '/medications/ndc_crawl', // 替换成你的实际路由
  method: 'GET',
  dataType: 'text', // 指定接收纯文本
  success: function(content) {
    // 用<pre>标签展示,它会自动保留文本的换行、缩进格式
    $('#your-display-element').html('<pre>' + content + '</pre>');
  }
});

方案2:返回JSON格式(前端需要额外处理数据时)

如果你需要把文本放在JSON的result字段里返回,那应该用render json而不是render text,这样Rails会正确序列化哈希为JSON字符串,前端解析后能拿到完整的原始文本。

控制器代码:

require "rinruby"
class MedicationsController < ApplicationController
  def ndc_crawl
    ndc = NDCCode.find_by(ndc_code: params[:ndc])
    ndc.crawl
    file_content = File.read("#{Rails.root}/product_info.txt")
    puts file_content
    // 返回JSON结构
    render json: { result: file_content }
  end
end

前端Ajax处理:

$.ajax({
  url: '/medications/ndc_crawl',
  method: 'GET',
  dataType: 'json',
  success: function(response) {
    // 取出result字段的文本,用<pre>标签展示
    $('#your-display-element').html('<pre>' + response.result + '</pre>');
  }
});

关键提醒

不管用哪种方案,前端展示时一定要用<pre>标签包裹文本,或者给容器设置CSS样式white-space: pre-wrap;,这样才能保留原文本的换行、空格和缩进格式——普通的<div>或<p>标签会把多个空格/换行合并成一个,这也是格式错乱的常见原因哦。

内容的提问来源于stack exchange,提问作者raven

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:21:54