`

Rails 返回hash给javascript

 
阅读更多
这是一个特别的,不太正统的需求,
因为,大部分时候,ajax的返回,只要返回json类型数据就可以了

然而,如果返回的是partial,partial里有变量是hash,而这个hash又需要jquery的plugin例如图表之类的用,那就需要这个rails的hash转成javascript能认,能读的hash了。

思路呢,还是通过json

就是在haml或者erb页面里吧hash转json
然后
jQuery.parseJSON( json )


var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );

或者

eval


另外,这样的转换,需要比较标准的json格式,要一般的转换参考用下面的
https://github.com/douglascrockford/JSON-js

引用
JavaScript is a general purpose programming language that was introduced as the page scripting language for Netscape Navigator. It is still widely believed to be a subset of Java, but it is not. It is a Scheme-like language with C-like syntax and soft objects. JavaScript was standardized in the ECMAScript Language Specification, Third Edition.

JSON is a subset of the object literal notation of JavaScript. Since JSON is a subset of JavaScript, it can be used in the language with no muss or fuss.

var myJSONObject = {"bindings": [
        {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},
        {"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"},
        {"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"}
    ]
};
In this example, an object is created containing a single member "bindings", which contains an array containing three objects, each containing "ircEvent", "method", and "regex" members.

Members can be retrieved using dot or subscript operators.

myJSONObject.bindings[0].method    // "newURI"
To convert a JSON text into an object, you can use the eval() function. eval() invokes the JavaScript compiler. Since JSON is a proper subset of JavaScript, the compiler will correctly parse the text and produce an object structure. The text must be wrapped in parens to avoid tripping on an ambiguity in JavaScript's syntax.

var myObject = eval('(' + myJSONtext + ')');
The eval function is very fast. However, it can compile and execute any JavaScript program, so there can be security issues. The use of eval is indicated when the source is trusted and competent. It is much safer to use a JSON parser. In web applications over XMLHttpRequest, communication is permitted only to the same origin that provide that page, so it is trusted. But it might not be competent. If the server is not rigorous in its JSON encoding, or if it does not scrupulously validate all of its inputs, then it could deliver invalid JSON text that could be carrying dangerous script. The eval function would execute the script, unleashing its malice.

To defend against this, a JSON parser should be used. A JSON parser will recognize only JSON text, rejecting all scripts. In browsers that provide native JSON support, JSON parsers are also much faster than eval. It is expected that native JSON support will be included in the next ECMAScript standard.

var myObject = JSON.parse(myJSONtext, reviver);
The optional reviver parameter is a function that will be called for every key and value at every level of the final result. Each value will be replaced by the result of the reviver function. This can be used to reform generic objects into instances of pseudoclasses, or to transform date strings into Date objects.

myData = JSON.parse(text, function (key, value) {
    var type;
    if (value && typeof value === 'object') {
        type = value.type;
        if (typeof type === 'string' && typeof window[type] === 'function') {
            return new (window[type])(value);
        }
    }
    return value;
});
A JSON stringifier goes in the opposite direction, converting JavaScript data structures into JSON text. JSON does not support cyclic data structures, so be careful to not give cyclical structures to the JSON stringifier.

var myJSONText = JSON.stringify(myObject, replacer);
If the stringify method sees an object that contains a toJSON method, it calls that method, and stringifies the value returned. This allows an object to determine its own JSON representation.

The stringifier method can take an optional array of strings. These strings are used to select the properties that will be included in the JSON text.

The stringifier method can take an optional replacer function. It will be called after the toJSON method (if there is one) on each of the values in the structure. It will be passed each key and value as parameters, and this will be bound to object holding the key. The value returned will be stringified.

Values that do not have a representation in JSON (such as functions and undefined) are excluded.

Nonfinite numbers are replaced with null. To substitute other values, you could use a replacer function like this:

function replacer(key, value) {
    if (typeof value === 'number' && !isFinite(value)) {
        return String(value);
    }
    return value;
}

var myJSONObject = {"bindings": [
        {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},
        {"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"},
        {"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"}
    ]
};

分享到:
评论

相关推荐

    Agile Web Development with Rails中文版 3rd Edition

    介绍了如何扩展Hash类,使其更具功能性。 **16.4 字符串扩展** 探讨了如何通过ActiveSupport扩展String类。 **16.5 数值的扩展** 讲解了如何通过ActiveSupport扩展数字类。 **16.6 时间和日期的扩展** 介绍了...

    rails-chart:Rails 应用程序的漂亮图表

    带有预配置 Javascript、AJAX 数据加载、干净的 HTML 和帮助程序的 Rails 应用程序的漂亮图表 安装 将此行添加到应用程序的 Gemfile 中: gem 'rails_chart' 然后执行: $ bundle 或者自己安装: $ gem ...

    Web开发敏捷之道-应用Rails进行敏捷Web开发-第三版.rar

    9.5 迭代D5:JavaScript被禁用时的对策 99 9.6 我们做了什么 99 第10章 任务E:付账! 101 10.1 迭代E1:收集订单信息 101 第11章 任务F:管理 113 11.1 迭代F1:添加用户 113 11.2 迭代F2:登录 120 11.3 迭代F3:...

    如何使用 Rails 和七牛云存储,在 15 分钟内打造一个图片分享社交应用原型

    运行 `rails generate scaffold post title filename qiniu_hash` 命令,将生成处理图片发表所需的模型、控制器、视图和数据库迁移文件。执行 `rake db:migrate` 完成数据库迁移,然后在浏览器中访问 `...

    jquery-bbq-rails

    请参阅以了解详细信息安装将此行添加到您的应用程序的Gemfile中: gem 'jquery_bbq_rails' 将以下指令添加到您的Javascript清单文件(application.js): //= require jquery_bbq版本控制jquery_b

    snackbarjs-rails:使用 Snackbar.js 提供更好的消息

    用于 Rails 的 SnackbarJS 见演示: : 安装将此行添加到应用程序的 Gemfile 中: gem 'snackbarjs-rails' 然后执行: $ bundle或者自己安装: $ gem install snackbarjs-rails用法应用程序.js //= require snackbar ...

    sozluk:Rails 的字典实验

    在Ruby on Rails(简称Rails)框架中,字典通常指的是哈希(Hash),它是Ruby语言的一个核心数据结构,用于存储键值对。在Rails中,哈希常用于表示数据库记录,如ActiveRecord对象的属性,或者在视图中传递上下文...

    針對 netzke 使用 authlogic 做登录验证

    3. **设置数据库**:更新迁移文件以添加必要的字段,如username、email和password_hash等,然后运行`rails db:migrate`。 4. **配置Authlogic**:在User模型中启用Authlogic,设置加密策略(如BCrypt)并配置其他...

    Web开发敏捷之道第三版(中文版).pdf

    - **迭代D5:JavaScript被禁用时的对策**:确保在JavaScript未启用的情况下也能正常使用购物车功能。 #### 第10章:任务E:付账 - **迭代E1:收集订单信息**:获取用户的订单信息,为结账做准备。 #### 第11章:...

    leetcode和洛谷-awesome-venados:由鹿屋策划并为鹿屋策划的资源集合

    leetcode和洛谷 令人敬畏的毒液 :deer: Una colección de recursos curados por y para la casa de los venados。...Rails ...Rails ...Javascript ...JavaScript ...Aircrack-ng/Hashcat 破解 WPA/WPA2 Wi-Fi 路由器

    Ruby-Sprockets基于Rack的资源打包系统

    5. **版本控制**:Sprockets通过添加指纹(hash值)到打包文件名来实现缓存 busting,确保当资源更新时,浏览器会获取新的版本而不是使用缓存的旧版本。这在部署新版本应用时非常有用,避免了用户看到过期的样式或...

    code-challenges:JavaScript,Ruby,Python和Shell脚本中的解决方案所带来的一系列代码挑战

    接下来是Ruby,一种注重简洁性和生产力的动态类型语言,常用于Web开发(如Rails框架)。Ruby挑战可能涵盖: 1. 元编程:Ruby的动态特性允许在运行时修改类和对象,这是其元编程能力的体现。 2. 魔法方法:了解如`...

    howmany---s:词歌词的词频计算器

    在这个特定项目中,团队通过Rails搭建了一个后端系统,该系统能够接收歌词数据,进行处理,并返回词频统计结果。 在Ruby中,可以使用内建的数据结构如哈希(Hash)来存储每个单词及其出现的次数,然后通过遍历歌词...

    phx_in_place:凤凰城应用程序的内联编辑

    该软件包包括一个视图帮助器,javascript事件侦听器和一个服务器端通道帮助器方法,该方法在设置时将在用户更改字段值时自动更新您的应用程序数据库和视图。 基本范例: < %= phx_in_place @ product , : ...

    Webapp Architecture

    - **Hash/Routing & Bookmarking**:使用浏览器的历史API和hash值来进行页面导航。 - **routes.js**:轻量级的路由管理库。 - **History.js**:支持多种浏览器的历史管理。 - **Ben Alman 的BBQ & hashchange**:...

    Ruby语言教程.docx

    - **游戏开发:** 虽然不如Python或JavaScript那样常用,Ruby也可以用于游戏开发。 通过上述知识点的总结,我们可以看出Ruby不仅是一种功能强大的编程语言,而且具有广泛的适用性和灵活性,适用于多种不同的开发...

    alley-fit:个人培训客户关系管理

    2. **用户界面**:使用Ruby on Rails框架构建的Web应用程序通常包含HTML、CSS和JavaScript,用于创建用户友好的界面。Rails的erb模板引擎将Ruby代码嵌入到HTML中,使得动态内容生成成为可能。 3. **数据库集成**:...

    Ruby与JSON:无缝数据交换的秘诀

    - **Ruby on Rails**:Ruby on Rails是一个流行的服务器端Web应用框架,用于构建数据库驱动的应用程序。 #### JSON简介 JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于阅读和编写,也便于...

    中科院高级软件工程期末题库

    JavaScript 函数是第一类公民,这意味着它们可以赋值给变量、作为参数传递以及返回其他函数。此外,JavaScript 支持闭包,使得函数可以访问它们创建时的作用域内的变量。 ### HTML HTML (HyperText Markup ...

Global site tag (gtag.js) - Google Analytics