提交前执行 javascript

Execute javascript before submit

我知道标题听起来与其他一些线程类似,但它有点 different.I 很少有像这样的按钮:

<input type=button name=Ok onclick='window.location="www.bla.com/bla.php"'>

当用户按下其中任何一个时,我想要一个 javascript 或 jquery 代码到 运行,但是之后,我想被发送到 www.bla。 com/bla.php.

我有一个 jquery 代码用于提交表单:

$( document ).ready(function() {
   $(':button').click(function(){
    document.getElementById('contact').submit();    
    }); 

jquery 代码有效,但按钮无效...

试试这个

<input class="btn" type=button name=Ok data-href="location">

$( document ).ready(function() {
   $('.btn').click(function(){

    // as you have used jQuery selector you can use it here like this 
    $('#contact').submit();   

    var location = $(this).attr("data-href");

    window.location.href  =  location;
    }); 
});

我的解决方案基于jQuery。

这里的语法不正确:

<input type=button name=Ok onclick="www.bla.com/bla.php">

修改为:

<input type=button name=Ok data-href="www.bla.com/bla.php">

jQuery:

$( document ).ready(function() {
  $(':button').click(function(){
  var hrefCurr = $(this).attr('data-href');
  document.getElementById('contact').submit();
  window.location.href = hrefCurr;
});

像这样的东西可以完成这项工作吗?

<input type='button' name='ok_btn' id='ok_btn' value='Ok'  data-href="www.bla.com/bla.php" />

$(document).ready(
    function() {
        $('#ok_btn).on('click',function(){
            // Do your stuff
            // Finally:
            window.location.replace($(this).attr('data-href'));
        });
    }
);

没有javascript会在表单提交后执行。表单提交更改 window.location,这会阻止旧 window.location 中的 javascript 执行。

但你可以伪造它。

  • 使用 jquery 表单提交表单(如果 CORS 允许的话)

  • 或者让表单目标处的脚本重定向到您想要的位置。

  • 或者提交到所需的位置,然后让脚本将表单数据发送到它应该去的地方