简体   繁体   English

在.Net代码之前触发Javascript

[英]Fire Javascript before .Net code

Our client want to be able to run some javascript tracking code when users click on a link to download a PDF. 当用户点击链接下载PDF时,我们的客户希望能够运行一些JavaScript跟踪代码。 My solution is to pass the name of the file, as a querystring, to a page that then prompts the user to download the file. 我的解决方案是将文件名作为查询字符串传递给页面,然后提示用户下载文件。 Is there anyway to get the javascript to run before the .net code? 反正有没有在.net代码之前运行javascript?

This is what I'm using on the file download page: 这就是我在文件下载页面上使用的内容:

public partial class FileTracking : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string pdf = Request["pdf"] ?? string.Empty;

        if (string.IsNullOrEmpty(pdf)) return;

        Response.Clear();
        Response.AppendHeader("content-disposition", "attachment; filename=" + pdf);
        Response.ContentType = "application/octet-stream";
        Response.WriteFile(pdf);
        Response.Flush();
        Response.End();
    }
}

Without seeing the javascript code, it's difficult to assess fully. 没有看到javascript代码,很难完全评估。 However, IF you were using jquery, then it would of course be possible to intercept the click on the link by doing something akin to the following: 但是,如果您使用的是jquery,那么当然可以通过执行类似于以下操作来拦截链接上的点击:

$('.myLink' data-filename='warandpeace.pdf' data-file-url="/file/history").click(function(e){
    var fileName = $(this).data('filename');
    var url = $(this).data('file-url');
    // this prevents the link actioning straight away
    e.preventDefault();
    // do your tracking stuff here 
    trackMyStuff(fileName);
    // invoke your file download now
    downloadMyFile(fileName, url);
    return false;
});

Hope this helps... 希望这可以帮助...

[edit] - added some in-line data attrs to show a fuller example.. [编辑] - 添加一些内联数据attrs以显示更完整的示例..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM