什么是嵌入的JavaScript code内是恒定的服务器端代码的最佳方式? [英] What's the best way to embed constant server-side tags inside javascript code?

查看:119
本文介绍了什么是嵌入的JavaScript code内是恒定的服务器端代码的最佳方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆依赖于一些服务器端常数(比如从我的资源文件中的字符串)的JavaScript函数。虽然我是开发他们我一直在视图标题的JavaScript code,这样我就可以只是用我的javascript code里面的服务器端代码,但现在我想移动的JavaScript函数到一个单独的文件。

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.

,因为那会不会是服务器PTED间$ P $,使得服务器标签内嵌有没有用,我不能使用常规的js文件。我不想定义页面变量,无论是因为这似乎办法尴尬,而且容易出错。

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.

我所做的反而是创建一个新的aspx文件,把JavaScript函数那里,包括aspx文件,而不是在我的主模板一个普通的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.

有什么缺点我的方法,我还没有考虑到?或者有什么更好的(不模糊)的方法?

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

修改奖金的问题:我应该使用DOCTYPE包含的脚本文件里面?毕竟,脚本文件是由脚本标签已经包括在内。我试图模仿常规js文件,所以我没有指定任何DOCTYPE。

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.

推荐答案

使用视图,MVC的模板功能,是实现这一目标的好方法。这是很容易维护,充分理解并得到快速的完成任务。唯一真正的关键是要得到它服务于正确的内容类型。做这样的事情:

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:

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

其实让你text / html的内容类型。关键是要确保你得到的最后一个字,它添加到你的控制器:

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

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

,你会得到正确的内​​容类型;似乎的ViewResult迫使它去text / html的。

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

这篇关于什么是嵌入的JavaScript code内是恒定的服务器端代码的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆