【问题标题】:Razor + JS Uncaught SyntaxError: Invalid or unexpected tokenRazor + JS Uncaught SyntaxError:无效或意外令牌
【发布时间】:2016-09-16 08:00:06
【问题描述】:

我有这个代码:

var tempPath = "@Path.GetTempPath()";
var blobURL = tempPath + "image.jpg";

我在检查页面时收到此错误:

未捕获的 SyntaxError:无效或意外令牌

这行是下划线的:

var tempPath = "C:\Windows\TEMP\";

这可能是一个愚蠢的解决方案,但我似乎无法找到它。我希望我的 blob-URL 是 C:\Windows\TEMP\image.png 所以我可以像这样使用它:

<img src="C:\Windows\TEMP\image.png"/>

编辑: 我不想硬核这条临时路径,因为我不知道它是否总是一样。

【问题讨论】:

    标签: javascript asp.net razor


    【解决方案1】:

    以下 JavaScript 无效:

    var tempPath = "C:\Windows\TEMP\";  // look at code highlighting
    console.log(tempPath); // and at the result of execution

    问题是 \ 反斜杠应该在 JS 字符串中转义。
    您需要以这种方式转义反斜杠:

    var tempPath = "C:\\Windows\\TEMP\\";
    console.log(tempPath);

    为了使用 Razor 实现此目的,您可以执行以下操作:

    var tempPath = "@HttpUtility.JavaScriptStringEncode(Path.GetTempPath())";
    

    【讨论】:

      猜你喜欢
      • 2021-08-14
      • 2020-07-12
      • 2017-09-29
      • 2018-12-03
      • 2017-01-22
      • 1970-01-01
      • 2018-05-12
      • 1970-01-01
      • 2021-09-21
      相关资源
      最近更新 更多