简体   繁体   English

如何使用ExtJS从Ruby on Rails中读取JSON

[英]How to read JSON from Ruby on Rails with ExtJS

I have some existing projects that were built upon a deprecated PHP framework, and I'm hoping to move them over to Ruby on Rails with minimal effort. 我有一些基于弃用的PHP框架构建的现有项目,我希望以最小的努力将它们转移到Ruby on Rails。 My main problem right now is the format that the JSON is coming back in. My frontend code (all ExtJS) is expecting JSON in the format: 我现在的主要问题是JSON重新出现的格式。我的前端代码(所有ExtJS)期望格式为:

{
    "result": [
        [id: 1, name: "mike"],
        [id: 2, name: "john"],
        [id: 3, name: "gary"]
    ]
}

But the default return from Ruby on Rails is as follows: 但Ruby on Rails的默认返回如下:

{
    "result": [
        {"record" : {id: 1, name: "mike"}},
        {"record" : {id: 2, name: "john"}},
        {"record" : {id: 3, name: "gary"}}
    ]
}

My controller is basically doing nothing but: 我的控制器基本上什么都不做,但:

@records = Record.find(:all)
respond_to do |format|
  format.json { render :text => @records.to_json}
end

As you can see, it's adding in an additional key to every record, which my frontend ExtJS code is not capable of parsing as-is. 正如您所看到的,它为每条记录添加了一个额外的键,我的前端ExtJS代码无法按原样解析。 Is there any way to stop this from occuring? 有没有办法阻止这种情况发生?

Thanks for any help you can offer, 谢谢你的尽心帮助,

Mike Trpcic 迈克Trpcic

basically : 基本上:

ActiveRecord::Base.include_root_in_json = false

or 要么

YourClass.include_root_in_json = false

as described here: http://apidock.com/rails/ActiveRecord/Serialization/to_json 如下所述: http//apidock.com/rails/ActiveRecord/Serialization/to_json

This question can now be closed, but I feel it relevant that I post the solution for anyone in the future who runs into the same situation. 现在可以关闭这个问题了,但我觉得相关的是我为将来遇到相同情况的人发布解决方案。 You can use the following plugin: Ext Scaffold Generator . 您可以使用以下插件: Ext Scaffold Generator even if you don't wish to use the scaffold functionality, it adds an additional "to_ext_json" method that outputs JSON that is readable by ExtJS by default. 即使您不希望使用脚手架功能,它也会添加一个额外的“to_ext_json”方法,该方法输出默认情况下ExtJS可读的JSON。

Thanks to anyone who looked into the matter and tried to help me. 感谢任何调查此事并试图帮助我的人。

You could also try: 你也可以尝试:

@records = Record.find(:all)
respond_to do |format|
  format.json { render :json => @records.map {|r| r.attributes } }
end

Here's a pattern that works for me: 这是一个适合我的模式:

format.json { render :json =>  {
          :rows => @data_array,
          :results => @data_array.length
        }, :callback => params[:callback]}

HTH HTH

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

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