【问题标题】:Javascript function to open a file not getting calledJavascript函数打开一个没有被调用的文件
【发布时间】:2012-05-24 11:00:52
【问题描述】:

我在调用 javascript 函数时遇到问题
我想通过点击链接打开文件。

这是我的代码:

<script language="javascript" type="text/javascript">
var refViewer = null;

function OpenViewerWindow(image) {
    return window.open(image, "Viewer", "height=400px,width=550px,menubar=no,scrollbars=yes ,resizable=yes,top=100px,left=234px");

}


function openViewer(image) {

    if (refViewer != null) {
        if (refViewer.closed == false) {
            refViewer.close();
            refViewer = OpenViewerWindow(image);
        }
        else refViewer = OpenViewerWindow(image);
    }
    else
        refViewer = OpenViewerWindow(image);
}   


</script>

<a onclick=javascript:openViewer(@ViewBag.path)><img src="pic.jpg"/></a>

在控制器中:

 public ActionResult ActivityPosting(int HobbyDetailID)
    {
string filepath = Server.MapPath("~/ePortfolio/PortFolioContent/" + HobbyDetailID + "/ReferenceMaterial/" + item.FilePath);
 ViewBag.path = filepath;
    return view();
   }

问题是javascript函数没有被调用。请帮助我

【问题讨论】:

    标签: javascript asp.net-mvc-3 asp.net-mvc-ajax


    【解决方案1】:

    在你的 JavaScript OpenViewerWindow 函数中试试这个(你需要使用 file:// 协议:

    return window.open("file://" + image, "Viewer", "height=400px,width=550px,menubar=no,scrollbars=yes   ,resizable=yes,top=100px,left=234px")
    

    【讨论】:

    • 问题是 openViewer() 函数本身没有被调用
    • 尝试将您的 a 标签更改为:&lt;a onclick="openViewer('@ViewBag.path');"&gt;&lt;img src="pic.jpg"/&gt;&lt;/a&gt;
    • 你能告诉我们你在@ViewBag.path 变量中的exact 文件路径,那个窗口试图打开吗?那一定是错的。
    • 你的文件路径是:E:\HOBBYHOMES(E-PORTFOLIO)\ePortfolio\e-Portfolio\PortFolioContent\1\ReferenceMaterial\prtf_1.docx
    • 啊,试试我的编辑,它必须以 file:/// 而不是 file:// 我最初输入的内容开头:)
    【解决方案2】:

    确保传递一个字符串:

    <a onclick=javascript:openViewer('@ViewBag.path')><img src="pic.jpg"/></a>
    

    注意单引号。或者甚至更好地使用 Json.Encode 来确保正确编码传递给您的 openViewer javascript 函数的值:

    <a onclick="javascript:openViewer(@Html.Raw(Json.Encode(ViewBag.path)))"><img src="pic.jpg"/></a>
    

    您的代码还有另一个问题。您使用 Server.MapPath 计算 url,但此方法返回服务器上文件的绝对路径。客户端显然无法使用绝对路径访问它。您应该使用 Url.Content 助手传递一个 url:

    public ActionResult ActivityPosting(int HobbyDetailID)
    {
        string filepath = Url.Content("~/ePortfolio/PortFolioContent/" + HobbyDetailID + "/ReferenceMaterial/" + item.FilePath");
        ViewBag.path = filepath;
        return View();
    }
    

    【讨论】:

    • 糟糕,那是因为我忘记在我的示例中设置ViewBag.path = filepath;。我已经更新了。
    • 函数被调用但文件没有打开
    • 这是您请求的网址的另一个问题。也许它有一些问题。
    猜你喜欢
    • 2011-12-30
    • 2018-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多