2013-10-23 31 views
1

我想調用一個點擊事件,然後按照href url。jQuery點擊事件第一,然後按照網址

HTML鏈接:

<a class="autoSave" href="?year=2013&amp;week=42">←</a> 

JS:

$(document).ready(function() { 

    $('.autoSave').click(function(event){ 
     event.preventDefault(); 
     $('.submitForm').click(); //HTML Form that I'm wanting a submit to happen 
     window.location = $(this).attr('href'); 
    }); 

}); 

上面的代碼將只需按照網址,而不是提交表單。如果我省略了window.location調用,則提交工作。

+1

是您的形式標準POST/GET HTML形式,或者它有一個基於AJAX的POST方法? –

+0

我的表單是標準POST – user1040259

回答

5

你不等待.click()事件完全處理調用window.location

您應該序列的形式,通過AJAX(與.post()例如)發佈它,然後,在.post()的回調,改變你的頁面:

$(document).ready(function() { 

    $('.autoSave').click(function(event){ 
     event.preventDefault(); 
     var serializedData = $('#yourForm').serialize(); //For example 
     $.post('your/path/to/form/validator', serializedData, function(){ 
      window.location = $(this).attr('href'); 
     }); 
    }); 
}); 
0

給你的表格一個id並使用submit()函數來提交它。在ID上使用jQuery選擇器而不是類,特別是如果您回收了您提供的類。

HTML

<form id="submitForm">...</form> 

的Javascript

$(document).ready(function() { 
    $('.autoSave').click(function(event){ 
     event.preventDefault(); 
     $('#submitForm').submit(); 
     window.location = $(this).attr('href'); 
    }); 
}); 
+0

由於他的表單是帖子,因此您不能發佈數據並進行重定向。這是一個或另一個沒有使用非常措施(彈出與父母重定向等)。 –

0

如果你的表格是一個標準的形式,最容易做的事情是設置一個隱藏的輸入字段值到後續網址:

$(document).ready(function() { 

    $('.autoSave').click(function(event){ 
     event.preventDefault(); 
     $('#redirectUrl').val($(this).attr('href')); 
     $('.submitForm').click(); //HTML Form that I'm wanting a submit to happen 
    }); 

}); 

在這種情況下,您將必須完全控制服務器端,您將能夠測試該值並執行301.

這遠非理想。有很多選項,但幾乎所有的選項都是黑客,以便從單個事件中重複發佈。

2

你不能做一個表單提交沒有瀏覽器試圖遵循表單操作。您需要使用ajax將自動保存的數據發佈到提交表單,然後在ajax成功返回時執行窗口重定向。

$('.autoSave').click(function(event){ 
    event.preventDefault(); 
    $.ajax({ 
     url: "whatever your submitForm.click() file is", 
     type: "POST", 
     data: { 
     formField: theValue 
     anotherFormField: theValue, 
    }, 
    success: function(data) { 
     window.location = $(this).attr('href');   
    } 
    }); 
} 
0

的問題是,瀏覽器不會等到它卸載的頁面,並遵循鏈接之前的M提交完成。

我建議你移動位置重定向您的表單提交的結尾:

$('.autoSave').on('click', function(event){ 
    event.preventDefault(); 
    $('.submitForm').triggerHandler('submit', [$(this).attr('href')]); 
}); 

$('.submitForm').on('submit', function(event, url) { 
// Do the thing 
window.location = url; 
}) 
相關問題