在javascript代码中嵌入常量服务器端标记的最佳方式是什么?

时间:2023-01-22 20:16:54

I have a bunch of javascript functions which depend on some server-side constants (such as strings from my resources file). While I was developing them I kept the javascript code in the view header, so I could simply used server-side tags inside my javascript code, but now I'd like to move the javascript functions to a separate file.

我有一堆javascript函数,它们依赖于一些服务器端常量(比如来自资源文件的字符串)。在开发它们时,我将javascript代码保存在视图头中,因此我可以在javascript代码中使用服务器端标记,但是现在我想将javascript函数移动到一个单独的文件中。

I can't use a regular js file since that would not be interpreted by the server, making the server tags embedded there useless. I don't want to define variables in the page either since that seems way to awkward and error-prone.

我不能使用一个普通的js文件,因为服务器不会解释这个文件,因此嵌入其中的服务器标记没有用处。我也不想在页面中定义变量,因为这看起来很笨拙,容易出错。

What I've done instead is to create a new aspx file, put the javascript functions there and include that aspx file instead of a regular js file in my master template. It seems a bit unorthodox, but it seems to work fine.

我所做的是创建一个新的aspx文件,将javascript函数放在那里,并在我的主模板中包含这个aspx文件,而不是一个普通的js文件。这看起来有点不正统,但似乎还不错。

Is there any downside to my approach that I have not taken into account? Or any better (less obscure) method?

我的方法是否有我没有考虑到的缺点?或者有更好的(不那么模糊的)方法吗?

Edit Bonus question: Should I use a DOCTYPE inside the included scripts file? After all, the scripts file is included by a script tag already. I tried to mimic regular js files, so I did not specify any DOCTYPE.

编辑附加问题:我应该在包含的脚本文件中使用DOCTYPE吗?毕竟,脚本文件已经包含在脚本标记中。我尝试模仿普通的js文件,所以没有指定任何DOCTYPE。

4 个解决方案

#1


2  

Using a view, with MVC's templating capabilities is a great way to accomplish this. It is easy to maintain, well understood and gets the job done fast. The only real trick is to get it to serve the correct content-type. Doing something like this:

使用视图,使用MVC的模板功能是实现这一点的好方法。它易于维护,易于理解,并能迅速完成工作。真正的诀窍是让它服务于正确的内容类型。做这样的:

    public ActionResult ConfigurationSettings()
    {
        Response.ContentType = "text/javascript";
        return View(Configuration);
    }

Actually gets you text/html content type. The trick is to make sure you get the last word, add this to your controller:

获取文本/html内容类型。关键是要确保你得到了最后一个单词,把它添加到你的控制器中:

    protected override void Execute(System.Web.Routing.RequestContext requestContext)
    {
        base.Execute(requestContext);
        requestContext.HttpContext.Response.ContentType = "text/javascript";
    }

And you will get the correct content type; ViewResult seems to force it to go text/html.

你会得到正确的内容类型;ViewResult似乎强制它进入文本/html。

#2


3  

The file extension, be it js, aspx, ashx, bla, foo, whatever isn't all that important. If you have server side generated javascript that isn't specific to a page, then creating an ASPX page to render the javascript should be okay.

文件扩展名,可能是js, aspx, ashx, bla, foo,任何不重要的。如果服务器端生成的javascript不是特定于页面的,那么创建一个ASPX页面来呈现javascript应该没问题。

We'll often use HTTP handlers to generate dynamic javvascript in our systems. We also make sure to set the response headers to text/javascript to let the client browser know that we are sending back javascript.

我们经常使用HTTP处理程序在系统中生成动态的javvascript。我们还确保将响应头设置为文本/javascript,以让客户机浏览器知道我们正在发回javascript。

#3


1  

We use the ScriptDataBlock control from JsonFx to emit variables into the page itself. It acts like a dictionary where the key is the variable name (e.g. "MyNamespace.myVar") and the value is a normal C# value (including whole objects). The control emits appropriate namespace generation and type conversion to native JavaScript types. So in that sense it ends up not being "awkward" or "error prone":

我们使用JsonFx的ScriptDataBlock控件将变量发送到页面本身。它就像一个字典,它的键是变量名(例如。“MyNamespace.myVar”)和值是一个普通的c#值(包括整个对象)。控件发出适当的名称空间生成和类型转换到本地JavaScript类型。因此,从这个意义上说,它最终不会是“尴尬的”或“容易出错的”:

myDataBlock["MyApp.myVar"] = myObject;

If you are doing an external file, then a generic .ashx handler is probably your best bet. It will be lighter than a whole aspx page and gives you pretty raw control over the output. Things you will want to be sure to do are to set the "Content-Type" response header to "text/javascript" (technically incorrect but most common MIME type) and for Internet Explorer which tends to not respect the Content-Type header, also set the "Content-Disposition" header to "inline;MyScriptName.js" so it knows the extension of the content.

如果您正在执行一个外部文件,那么一个通用的.ashx处理程序可能是您最好的选择。它将比整个aspx页面更轻,并为您提供对输出的基本控制。您需要确保的事情是将“Content-Type”响应头设置为“text/javascript”(技术上不正确,但最常见的MIME类型),对于不尊重Content-Type报头的Internet Explorer,还将“content -处置”报头设置为“inline;MyScriptName”。所以它知道内容的扩展。

Also, if these really are "constants" rather than runtime calculated data, you will want to set the "Expires" header to some future date to encourage the browser to cache the result. That will further reduce your server requests.

此外,如果这些实际上是“常量”而不是运行时计算的数据,您将希望将“Expires”标题设置为某个未来日期,以鼓励浏览器缓存结果。这将进一步减少您的服务器请求。

Edit: no DocType if you are creating JavaScript. DocType is only for markup.

编辑:如果您正在创建JavaScript,没有DocType。DocType仅用于标记。

#4


1  

You are using the MVC framework (your question is tagged as such) right? If so, you can create an action that returns a JavaScriptResult that will be executed on page when it loads:

您正在使用MVC框架(您的问题被标记为这样)对吗?如果是,您可以创建一个动作,返回一个javascript脚本,当它加载时将在页面上执行:

public class JSController : Controller {
    public ActionResult Headers() {
        // create your variables here
        return JavaScript("alert('hi');");
    }
}

And then you can add it to your aspx/master page:

然后你可以把它添加到你的aspx/master页面:

<script src="/JS/Headers" type="text/javascript"></script>

#1


2  

Using a view, with MVC's templating capabilities is a great way to accomplish this. It is easy to maintain, well understood and gets the job done fast. The only real trick is to get it to serve the correct content-type. Doing something like this:

使用视图,使用MVC的模板功能是实现这一点的好方法。它易于维护,易于理解,并能迅速完成工作。真正的诀窍是让它服务于正确的内容类型。做这样的:

    public ActionResult ConfigurationSettings()
    {
        Response.ContentType = "text/javascript";
        return View(Configuration);
    }

Actually gets you text/html content type. The trick is to make sure you get the last word, add this to your controller:

获取文本/html内容类型。关键是要确保你得到了最后一个单词,把它添加到你的控制器中:

    protected override void Execute(System.Web.Routing.RequestContext requestContext)
    {
        base.Execute(requestContext);
        requestContext.HttpContext.Response.ContentType = "text/javascript";
    }

And you will get the correct content type; ViewResult seems to force it to go text/html.

你会得到正确的内容类型;ViewResult似乎强制它进入文本/html。

#2


3  

The file extension, be it js, aspx, ashx, bla, foo, whatever isn't all that important. If you have server side generated javascript that isn't specific to a page, then creating an ASPX page to render the javascript should be okay.

文件扩展名,可能是js, aspx, ashx, bla, foo,任何不重要的。如果服务器端生成的javascript不是特定于页面的,那么创建一个ASPX页面来呈现javascript应该没问题。

We'll often use HTTP handlers to generate dynamic javvascript in our systems. We also make sure to set the response headers to text/javascript to let the client browser know that we are sending back javascript.

我们经常使用HTTP处理程序在系统中生成动态的javvascript。我们还确保将响应头设置为文本/javascript,以让客户机浏览器知道我们正在发回javascript。

#3


1  

We use the ScriptDataBlock control from JsonFx to emit variables into the page itself. It acts like a dictionary where the key is the variable name (e.g. "MyNamespace.myVar") and the value is a normal C# value (including whole objects). The control emits appropriate namespace generation and type conversion to native JavaScript types. So in that sense it ends up not being "awkward" or "error prone":

我们使用JsonFx的ScriptDataBlock控件将变量发送到页面本身。它就像一个字典,它的键是变量名(例如。“MyNamespace.myVar”)和值是一个普通的c#值(包括整个对象)。控件发出适当的名称空间生成和类型转换到本地JavaScript类型。因此,从这个意义上说,它最终不会是“尴尬的”或“容易出错的”:

myDataBlock["MyApp.myVar"] = myObject;

If you are doing an external file, then a generic .ashx handler is probably your best bet. It will be lighter than a whole aspx page and gives you pretty raw control over the output. Things you will want to be sure to do are to set the "Content-Type" response header to "text/javascript" (technically incorrect but most common MIME type) and for Internet Explorer which tends to not respect the Content-Type header, also set the "Content-Disposition" header to "inline;MyScriptName.js" so it knows the extension of the content.

如果您正在执行一个外部文件,那么一个通用的.ashx处理程序可能是您最好的选择。它将比整个aspx页面更轻,并为您提供对输出的基本控制。您需要确保的事情是将“Content-Type”响应头设置为“text/javascript”(技术上不正确,但最常见的MIME类型),对于不尊重Content-Type报头的Internet Explorer,还将“content -处置”报头设置为“inline;MyScriptName”。所以它知道内容的扩展。

Also, if these really are "constants" rather than runtime calculated data, you will want to set the "Expires" header to some future date to encourage the browser to cache the result. That will further reduce your server requests.

此外,如果这些实际上是“常量”而不是运行时计算的数据,您将希望将“Expires”标题设置为某个未来日期,以鼓励浏览器缓存结果。这将进一步减少您的服务器请求。

Edit: no DocType if you are creating JavaScript. DocType is only for markup.

编辑:如果您正在创建JavaScript,没有DocType。DocType仅用于标记。

#4


1  

You are using the MVC framework (your question is tagged as such) right? If so, you can create an action that returns a JavaScriptResult that will be executed on page when it loads:

您正在使用MVC框架(您的问题被标记为这样)对吗?如果是,您可以创建一个动作,返回一个javascript脚本,当它加载时将在页面上执行:

public class JSController : Controller {
    public ActionResult Headers() {
        // create your variables here
        return JavaScript("alert('hi');");
    }
}

And then you can add it to your aspx/master page:

然后你可以把它添加到你的aspx/master页面:

<script src="/JS/Headers" type="text/javascript"></script>