我正在使用 requirejs 为我的页面加载 JavaScript。我有一个 webApi 路由,它动态地从文件中读取并使用 Newtonsoft JObject 返回 JSON。然后在客户端,我获取结果并将其分配给本地 JavaScript 变量。
定义(['jquery'],函数($){
function dynoFile() { $.get('/api/resources/dynofile', function (results) { myNamespace.dynoFile = results; }); } return new dynoFile(); });
此示例确实有效,但它会导致其他期望 myNamespace.dynoFile 存在的 JavaScript 文件出现问题。由于这个文件加载得很好,其他文件不会等待 $.get 完成。
是否有可能让 web api 方法只返回 JavaScript 并让浏览器将其识别为 JavaScript 而不仅仅是文本?我尝试在 web api 中设置响应标头以及返回生成的脚本的多种方式。
这可能吗?
更新:
更详细一点,我正在使用我的 Web API 来处理我的资源文件并将 JSON 返回给客户端,因为它是一个单页应用程序。我希望只从我可以使用 RequireJS 加载的 Web API 返回 JavaScript。我现在将它作为 JSON 工作,并认为我会分享我所拥有的。
这是我的 WebApi 方法,它读取资源文件并将其作为 JSON 返回:
public JObject Get()
{
var data = new JObject();
var type = typeof(Translations);
var properties = type.GetProperties();
foreach (var property in properties)
{
if (property.Name != "ResourceManager" && property.Name != "Culture")
{
data.Add( property.Name, property.GetValue(type, null).ToString());
}
}
HttpContext.Current.Response.Headers.Add("Content-Type", "application/json");
return data;
}
这是我的 translations.js 文件:
define(['jquery', 'underscore'], function ($) {
function translations() {
}
_.extend(translations.prototype, {
target: '/api/resources/translations',
getTranslations: function () {
return $.ajax({
url: 'api/resources/translations',
type: 'GET',
dataType: 'json'
});
}
});
return (translations);
});
由于我的其他几个文件依赖于现有的翻译,我需要在我的 main.js 中嵌套 2 个 RequireJS 语句:
requirejs(['application/translations', 'whatever other resources that can load that don't depend on translations'], function () {
var trans = new translations();
trans.getTranslations()
.done(function (result) {
// set translations into a variable, we chose it to be part of the global namespace
window.Translations = result;
// load remaining dependencies that require translations to exist
requirejs(['myotherjsfiles', 'blahblah', function () {
// you get the idea...
});
});
});
这允许我的翻译首先加载(使用任何非依赖文件,如 bootstrap、jquery 等),然后加载我所有依赖的 JavaScript 文件。我还针对 RequireJs 优化方法对此进行了测试,它能够解决嵌套需求。希望这可以帮助其他人了解如何将翻译下载到客户端和/或如何使用 RequireJS 加载动态模块。
如果有人知道如何让 WebApi 返回 JavaScript,我很想听听!
干杯!