0

I am trying to consolidate all my javascript ajax calls into a Javascript Revealing Module. However there is 1 global javascript property called RootPath which is hard coded into the View page with an inpage script tag using:

var RootPath = '@Url.Content("~/")';

In a separate .js file I am creating calls to fetch JSON from my server side.

    var dataService = function () {
        var url = RootPath + "API/GetData",
        getData = function () {
            return $.getJSON(url);
        };

        return {
            getData: getData
        };
}();

Issue is that inside the Javascript object this global RootPath is undefined. How can I get this global property inside my object?

4

4 回答 4

0

如果您真的想使用那个“全局” RootPath 变量,您可以做的一件事是,

window.rootPath = '@Url.Content("~/")';

(这应该在布局页面中或在您知道它比 javascript 文件首先运行的地方)然后在您的 javascript 文件上执行,

var dataService = function () {
        var url = window.rootPath + "API/GetData",
        getData = function () {
            return $.getJSON(url);
        };

        return {
            getData: getData
        };
于 2013-10-14T13:42:01.263 回答
0

我过去曾使用过这种方法,效果很好:

<base href="@string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"))">

然后,您不需要为每个请求指定它。

基本标签的定义:http: //www.w3schools.com/tags/tag_base.asp

于 2013-10-14T13:22:30.833 回答
0

尝试将全局变量放在 page/layout.cs html 的顶部;

<html><head>
</script type="text/javascript">
var RootPath = '@Url.Content("~/")';
</script>
<script src="my_jsfiles" type="text/javascript">

<head>

在顶层定义 js 将始终可以从页面的所有位置访问

于 2013-10-14T13:39:29.883 回答
-1

你能试试这个吗?

    var dataService = function () {
        var url = "/API/GetData",
        getData = function () {
            return $.getJSON(url);
        };

        return {
            getData: getData
        };
}();

请注意我已经删除了RootPath 变量并直接使用var url = "/API/GetData"了..试试这个我认为它应该可以工作

于 2013-10-14T13:23:59.550 回答