繁体   English   中英

导轨 json 格式

[英]rails json format

我正在尝试呈现 json 字符串以响应如下请求:

def check_progress
  if request.xhr?
    render :json=>"{'bytes_expected': #{session[:size]}, 'bytes_recieved': #{session[:size]}, 'last_seq': 0}".to_json
  end
end

但在我的js代码中:

$.getScript('contacts/check_progress', function(data){
    console.log(data.bytes_recieved)
    console.log(data.bytes_expected)
    d.renderProgress(data);
});

我得到 undefined 以响应data.bytes_recieveddata.bytes_expected

我的 Rails 代码有什么问题?

我认为您的主要问题可能是您返回的字符串看起来像 json 而实际上不是 json hash。

在您的渲染语句中,您正在手动将 json 格式化为字符串......这很好,直到您调用 to_json 。

to_json 应该传递一个 hash 而不是字符串。

您可以尝试在您的渲染语句末尾删除 .to_json :

render :json=>"{'bytes_expected': #{session[:size]}, 'bytes_recieved': #{session[:size]}, 'last_seq': 0}"

或创建 ruby hash 然后将其转换为 json:

@ruby_hash = {
  :bytes_expected => session[:size],
  :bytes_recieved => session[:size],
  :last_seq => 0
}

render :json=> @ruby_hash.to_json

jQuery 的$.getScript方法将<script>节点插入到 HTML 文档的<head>中。

使用这种方法,您的浏览器不会将X-Requested-With HTTP header 发送到服务器。 因为这将是一个简单的 HTTP 请求而不是 AJAX 请求。 您的浏览器正在等待响应中的 javascript 而不是 JSON 数据。

In the jQuery documentation of the $.getScript method is somewhat misleading because it says data in the callback function of the method signature, but it won't give you any data in the callback function, because your browser simply executes the javascript there is no此请求的实际有效负载。

有可能的解决方案:

  • 如果需要跨域加载数据,那么试试把request.xhr? 条件使用JSONP方法和回调
  • 如果不是跨域情况,只需使用$.getJSON响应加载并且不要触及条件

更新:我还没有看到它,但@Barlow 指出你需要按照他的说法在你的 Rails 应用程序中修复你的 json 生成代码。

您可以将代码简化为:

def check_progress
  if request.xhr?
    render :json => {'bytes_expected' => session[:size], 
                     'bytes_recieved' => session[:size], 
                     'last_seq' => 0}
  end
end

render:json将为您将 hash 转换为 JSON ZA8CFDE6331BD59EB2AC96F8911ZB4。 我不知道这是否能解决问题。

暂无
暂无

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

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