{ :id => "123456", :name => "Pa-6ren">
gpt4 book ai didi

javascript - 在 Rails 中创建的 JSON 字符串用加号 (+) 替换空格

转载 作者:行者123 更新时间:2023-11-30 09:01:32 25 4
gpt4 key购买 nike

rails :

object = Object.find_by(params[:id])

object_items = { "1" => { :id => "123456", :name => "Pancakes Yum!" }, "2" => { :id => "789010", :name => "hello 123" }}

cookies[:something] = { "id" => object.id, "title" => object.title, "object_items" => object_items }.to_json

假设 object.title 产生一个字符串“Hello World”

Cookie 内容:

%7B%22id%22%3A2%2C%22title%22%3A%22Hello+World%22%2C%22object_items%22%3A%7B%221%22%3A%7B%22id%22%3A%22123456%22%2C%22name%22%3A%22Pancakes+Yum!%22%7D%2C%222%22%3A%7B%22id%22%3A%22789010%22%2C%22name%22%3A%22hello+123%22%7D%7D%7D

问题:

正在创建的 JSON 字符串用加号 (+) 而不是 %20 替换/转义空格,这意味着如果我要读取字符串并获取HTML/JavaScript 中 object.title 的值,它将读作“Hello+World”而不是预期的“Hello World”。

所有其他字符似乎都被正确替换/转义 - 是因为双引号内存在空格吗?我不明白为什么它会按原样生成这个字符串。

最佳答案

我不明白您为什么要通过 cookie 与客户端通信。为什么不使用 Controller 操作和 ajax 请求?

class SomethingController
def show
object = Object.find_by(params[:id])

object_items = { "1" => { :id => "123456", :name => "Pancakes Yum!" }, "2" => { :id => "789010", :name => "hello 123" }}

render :json => { "id" => object.id, "title" => object.title, "object_items" => object_items }
end

然后使用 jQuery 或类似的东西请求它:

$.get('/something/1.json', function(results) { alert(results); });

如果您不打算使用 Rails,那么使用 Rails 有什么意义?

Cookie 在发送到客户端之前经过 CGI 转义。当客户端重新传输它们时,Rails 会取消转义它们。

您可以像这样测试行为:

rails console c
CGI.escape("something something")
=> "something+something"
CGI.unescape("something+something")
=> "something something"

关于javascript - 在 Rails 中创建的 JSON 字符串用加号 (+) 替换空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8840566/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com