在 JavaScript 中使用全局资源

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3649627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 01:50:07  来源:igfitidea点击:

Using global resource in JavaScript

javascriptasp.net

提问by emre

I want to use global resource in my javascript code. Normally, when the code is inside the ASP code, I use <%=GetGlobalResourceObject("Resource", "MONTHS_SHORT1") %>and it works. But, when the javascript code is not inside the ASP code, for example in a folder as calendar.js, it does not work. How can I use the global resource in this case? Note: The resource file is inside my App_GlobalResources folder.

我想在我的 javascript 代码中使用全局资源。通常,当代码在 ASP 代码中时,我使用 <%=GetGlobalResourceObject("Resource", "MONTHS_SHORT1") %>它并且它可以工作。但是,当 javascript 代码不在 ASP 代码中时,例如在一个文件夹中作为 calendar.js,它不起作用。在这种情况下如何使用全局资源?注意:资源文件位于我的 App_GlobalResources 文件夹中。

采纳答案by James Westgate

Look at the following post I created describing how you can serialise global and local resources and retrieve them from javascript using jQuery and JSON.

查看我创建的以下帖子,该帖子描述了如何序列化全局和本地资源并使用 jQuery 和 JSON 从 javascript 中检索它们。

http://bloggingdotnet.blogspot.com/2010_02_01_archive.html

http://bloggingdotnet.blogspot.com/2010_02_01_archive.html

Firstly, create a new handler (.ashx) file. This one was written quite some time ago, so uses vb.net and custom JSON serialisation:

首先,创建一个新的处理程序 (.ashx) 文件。这个是很久以前写的,所以使用 vb.net 和自定义 JSON 序列化:

Imports System.Web
Imports System.Web.Services
Imports System.Xml
Imports System.Resources
Imports System.Reflection

Public Class Localisation
  Implements System.Web.IHttpHandler

  Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
    Dim files As String = context.Request.QueryString("files")
    Dim local As String = context.Request.QueryString("local")
    Dim isLocal As Boolean
    Dim folder As String = "App_GlobalResources"

    context.Response.ContentType = "text/javascript"

    'Write out file as object
    context.Response.Write("{")

    'Determine if local resource file
    If local IsNot Nothing Then
      isLocal = CBool(local)
      If isLocal Then folder = "App_LocalResources"
    End If
    If files Is Nothing OrElse files.Length = 0 Then Throw New ArgumentException("Parameter 'files' was not provided in querystring.")

    Dim flag As Boolean = False
    For Each file As String In files.Split(",")
      If flag Then context.Response.Write(",")

      Dim className As String = file.Split(".")(0)

      'Write the class (name of the without any extensions) as the object
      context.Response.Write(className)
      context.Response.Write(":{")

      'Open the resx xml file
      Dim filePath As String = context.Server.MapPath("~\" & folder & "\" & file)
      Dim document As New XmlDocument()
      Dim flag2 As Boolean = False
      document.Load(filePath)

      Dim nodes As XmlNodeList = document.SelectNodes("//data")

      For Each node As XmlNode In nodes

        'Write out the comma seperator
        If flag2 Then context.Response.Write(",")

        Dim attr As XmlAttribute = node.Attributes("name")
        Dim resourceKey As String = attr.Value
        context.Response.Write(resourceKey)
        context.Response.Write(":""")

        'Write either the local or global value
        If isLocal Then
        context.Response.Write(HttpContext.GetLocalResourceObject(String.Format("~/{0}",    file.Replace(".resx", "")), resourceKey)) 'Has to be full path to the .aspx page
        Else
          context.Response.Write(HttpContext.GetGlobalResourceObject(className, resourceKey))
        End If
        context.Response.Write("""")

        'Flag that we need a comma seperator
        flag2 = True
      Next

      context.Response.Write("}")
      flag = True
    Next

    'End file
    context.Response.Write("}")
  End Sub

  Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
    Get
      Return True
    End Get
  End Property
End Class

When that is working, use the following jQuery code to make an ajax call to the http handler and return the contents of the resource file as an object literal.

当它起作用时,使用以下 jQuery 代码对 http 处理程序进行 ajax 调用,并将资源文件的内容作为对象文字返回。

// -- Localisation --
var localResources;
var globalResources;

//Sample JSON for javascript resource values eg {TrackDetail:{HideHelp:"Hide Help", ShowHelp:"Show Help"}}
//Usage e.g: alert(localResources.TrackDetail.HideHelp);

//Load Localisation values into variables so that they can be available on the client
//Note that these values are loaded asynchronously, the code in the function will not run until the call has completed.
$.getJSON('Localisation.ashx?files=TrackDetail.aspx.resx&local=true', function(data) { localResources = data});
$.getJSON('Localisation.ashx?files=Errors.resx,Strings.resx', function(data) { globalResources = data});

回答by SausageFingers

I often use a hidden literal to hold the resource text then grab the localised text using javascript and jquery:

我经常使用隐藏文字来保存资源文本,然后使用 javascript 和 jquery 获取本地化文本:

  <asp:Literal runat="server" ID="Literal1" visible="false" Text="<%$ Resources:String, MyResourceText%>" />
  <input type="button" id="Button1"  value=""  />
  <script type="text/javascript">
            $(document).ready(function () {
                // Update the buton text with the correct localised lookup
                var ButtonText = '<%=Literal1.Text%>';
                $("#Button1").attr('value', ButtonText );
            });
  </script>

回答by Christian Nesmark

You would have to generate JavaScript code that mimics the resources you need, as ASP.NET runs server-side, and JavaScript runs client-side.

您必须生成模仿所需资源的 JavaScript 代码,因为 ASP.NET 在服务器端运行,而 JavaScript 在客户端运行。

<script language="javascript" type="text/javascript">
var MONTHS_SHORT1 = <%=GetGlobalResourceObject("Resource", "MONTHS_SHORT1") %>;
</script>

回答by Harshada

This will register resource key.

这将注册资源密钥。

ClientScriptManager cs = Page.ClientScript;

String scriptRegVariables = string.Format("var resourcetext = '{0}'", Resources.Resource.keyText);
if (!cs.IsClientScriptBlockRegistered("RegVariablesScript"))
{
    cs.RegisterClientScriptBlock(typeof(_Default), "RegVariablesScript", scriptRegVariables, true);
}

Now inside .js file you can directly use it. e.g. Alert(resourcetext);

现在在 .js 文件中你可以直接使用它。例如警报(资源文本);

Add the code above on Page_Load of control or aspx page

在控件或aspx页面的Page_Load上添加上面的代码