【问题标题】:a href click delaying document download to run Ajaxa href 单击延迟文档下载以运行 Ajax
【发布时间】:2013-09-10 19:58:12
【问题描述】:

我遇到了一些代码问题。我有一个href 链接,点击后会下载一个文档。出于某种原因,这干扰了我的jQuery getJSON

当我添加e.preventDefault() 时,我的代码可以完美执行。当我注释掉e.preventDefault() 我的JSON 代码永远不会执行。

这是我的href链接:

<a href="http://server:88/Documents/@Html.DisplayFor(model => model.path)" data-docid="@Html.Raw(Model.documentID)" class="btn documentLock" data-toggle="modal">
                                Download Word Version</a>

这是我的 jQuery:

jQuery('.documentLock').click(function (e) {
        // Stop the default behavior
        e.preventDefault();

        var object = jQuery(this);
        var docid = object.attr('data-docid');

        jQuery.getJSON("/Document/LockedStatus/" + docid, null, function (data) {

        })
        .fail('Could not communicate with the server, if this persists please contact the Computer department')
        .success(function (data) {
            if (data) {
                console.log(data);
                jAlert('This document is currently locked by and cannot be edited further', 'Document Locked');

            }
        });
    });

使用e.preventDefault 我可以触发console.log(data)。使用e.preventDefault 它不会触发。所以我知道代码有效,它一定与下载文档的链接有关。

【问题讨论】:

  • 在成功回调中,尝试:object.get(0).click()
  • 我迷路了。单击链接将导致页面加载,这意味着当getJSON 调用返回时,您甚至不会在同一页面上。您想在通话结束之前停止链接工作吗?
  • @A.Wolff 我在这里没有看到你的评论。 object.get(0).click() 是否与放置 window.location = href; 相同?在我的成功回调中?
  • @JamesWilson 是的,它将具有与触发本机点击事件相同的行为(不是 jquery 之一)

标签: jquery ajax href


【解决方案1】:

将此添加到您的代码中

.done(function() { 
window.location.replace("your url"); // give your url here

})

这是您编辑的代码

jQuery('.documentLock').click(function (e) {
    // Stop the default behavior
    e.preventDefault();

    var object = jQuery(this);
    var docid = object.attr('data-docid');

    jQuery.getJSON("/Document/LockedStatus/" + docid, null, function (data) {

    })
        .fail('Could not communicate with the server, if this persists please contact the Computer department')
        .success(function (data) {
        if (data) {
            console.log(data);
            jAlert('This document is currently locked by and cannot be edited further', 'Document Locked');

        }
    })
  .done(function () {
        window.location.replace("your url"); // give your url here

    });
});

【讨论】:

  • 我实际上必须使用 e.preventDefault ,然后在我的 Ajax 执行后执行 window.location 。因为我需要两者都完成。
  • ajax调用后你重定向到另一个页面是什么?
  • 是的,所以我只是将 href 隐藏到一个 var 中,最后我 window.location = href。只有这样我才能让它工作。
【解决方案2】:

href 属性被顶起。如果您可以将其更改为 javascript:void(0); 或只是一个标签,那可能会有所帮助。

你为什么不使用.data()

把这个:var docid = object.attr('data-docid');改成这个:

var docid = object.data('docid');

【讨论】:

  • 为什么?在一个 DOM 节点的 jquery 对象中包装两次是错误的
  • jQuery()$() 相同
  • @Archer - 正如你所说的那样没有区别......所以猜想不需要改变任何东西。
猜你喜欢
  • 2019-04-09
  • 2015-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-18
  • 1970-01-01
  • 2021-07-30
  • 1970-01-01
相关资源
最近更新 更多