问题描述
我正在使用rails3.0.10
i'm using rails3.0.10
def districts
@names = Node.where("name like ?", "%#{params[:term]}%").limit(5).map(&:name)
respond_to do |format|
format.json {render :json => @names}
format.xml {render :xml => @names}
end
end
渲染xml获取正确的名称
但是渲染json使名称的编码方式类似于=> ["name1","name2","\ ufffd \ ufffd \ ufffd \ ufffd \ ufffd \ ufffd \ ufffd \ ufffd"]
我想用正确的语言来命名正确的名字
render xml get right names
but render json make the names is encoded like => ["name1", "name2", "\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd"]
i want to get right names in their right language
有什么帮助吗?
预先感谢
推荐答案
在发送响应之前,您必须将字符串强制为UTF-8
before sending the response you must force the strings to be UTF-8
为此行添加上面的代码
@names.map{|name| name.force_encoding('UTF-8')}
这将循环名称数组,并强制将它们从ASCII-8BIT编码为UTF-8
this will loop the array of names and force them to be encoded from ASCII-8BIT to UTF-8
所以我的方法将是
def districts
@names = Node.where("name like ?", "%#{params[:term]}%").limit(5).map(&:name)
@names.map{|name| name.force_encoding('UTF-8')}
respond_to do |format|
format.json {render :json => @names}
format.xml {render :xml => @names}
end
end
您还可以像
class Node < ActiveRecord::Base
def name
super().force_encoding('UTF-8')
end
end
我确定此代码可正常运行
谢谢
M.SH
i'm sure from this code , it works correctly
Thanks
M.SH
这篇关于渲染JSON但在Rails 3.0.1中编码字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!