(jQuery)如何在链接之前调用自定义函数 [英] (JQuery) How to call a custom function before following link

查看:83
本文介绍了(jQuery)如何在链接之前调用自定义函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在页面链接中实现以下行为.

I want to achieve the following behavior in a page link.

单击链接后,我要:

  • 首先,将一些数据发送(POST)回服务器
  • 第二,允许浏览器导航到链接所指向的URL.

我对JQuery比较陌生,这是我在下面的第一次尝试.我将感谢这里的所有jQuery专家来填补空白(并指出下面的代码段可能会得到改进).

I am relatively new to JQuery, and here is my first attempt below. I will be grateful to any jQuery gurus in here to fillin the blanks (and maybe point out how the snippet below may be improved).

<html>
<head>test page</head>
<body>
<div><a id="hotlink" href="http://www.example.com">Clik and see</a></div>
<script type="text/javascript">
$(document).ready(function(){
  $('hotlink').click(function(){
     //AJAX Post data here ...
     //follow the link url (i.e. navigate/browse to the link) ...
  });
});
</script>
</body>
</html>

推荐答案

您可能想看看我的

You might want to see my answer to a similar question. Basically, an ajax post would be asynchronous by default and may not make it to the server before completing. In order to ensure completion, you can make it synchronous but this will lock up the browser until the request has returned. This can be very problematic if your server is having trouble, it could take a while and the user is waiting to follow the link. Nevertheless, the code is:

$('#hotlink').click( function () { 
    $.ajax({ 
      async: false,
      type: "POST", 
      url: "http://myurl.com/mypage.php", 
      data: "param1=value&param2=value",  // &param3=value... etc. 
    }); 
}); 

完成后,将遵循该链接的默认操作.

Upon completion, the default action of the link will be honoured.

这篇关于(jQuery)如何在链接之前调用自定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆