大家都知道,要在.Net下实现国际化是很简单的事,只需添加一个 App_GlobalResources 目录和相应的资源文件(.resx),然后就可以直接调用了,如现有一资源文件名为: Admin.resx,其中有一个叫 Title 的键值,这时在页面只需直接使用
string title = Resources.Admin.Title;
但如果想在JS里也使用此资源文件,要如何处理呢?其实也很简单,只需使用AJAX调用后台获取资源文件即可,以下就使用jQuery + ASP.NET MVC为例实现在JS下直接调用资源文件的方法(当然你也可以直接使用传统的JS AJAX方法获取)
先创建获取资源文件的函数:
//使用键值方式获取资源文件,其中 category 即资源文件名
Resource = function (category, key) {
//使用jQuery的 ajax 直接获取相应的资源文件
var rtnvalue =
$.ajax({
type: "POST",
dataType: "json",
data: {
"category": category,
"key": key
},
url: "/GetResource",
async: false
}).responseText;
//返回 json 数据
var rtnvalue = $.parseJSON(rtnvalue);
if (!rtnvalue.MsgType)
return "No Resource File!";
else
return rtnvalue.Content;
}
Resource = function (category, key) {
//使用jQuery的 ajax 直接获取相应的资源文件
var rtnvalue =
$.ajax({
type: "POST",
dataType: "json",
data: {
"category": category,
"key": key
},
url: "/GetResource",
async: false
}).responseText;
//返回 json 数据
var rtnvalue = $.parseJSON(rtnvalue);
if (!rtnvalue.MsgType)
return "No Resource File!";
else
return rtnvalue.Content;
}