簡體   English   中英

jQuery表單插件,如何防止表單提交

[英]jQuery form plugin, how to prevent the form submit

我正在使用jQuery表單插件上傳文件並顯示進度欄。

JS代碼:

var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');

var options = { 
    target:     '.result', 
    url:        'slider_insert_now.php', 



    beforeSend: function() {


    var img_file = $.trim($(".img_file").val());

    if(img_file==$.trim('')){

    $(".result").html('<span class="error">No file selected</span>');


    return false; 

    }else{

    status.empty();
    var percentVal = '0%';
    bar.width(percentVal)
    percent.html(percentVal);

    return true;
 }


},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal)
percent.html(percentVal);
},
success: function() {
var percentVal = '100%';
bar.width(percentVal)
percent.html(percentVal);
},
complete: function(xhr) {
status.html(xhr.responseText);
}



}; 



$('#form_upload').ajaxForm(options);

和HTML:

<div class="result"></div>


    <form id="form_upload" action="javascript:void(0)" method="POST" enctype="multipart/form-data">

    <div class="progress">
<div class="bar"></div>
<div class="percent">0%</div>
</div>
<div id="status"></div>



    <input type="file" value="" name="img_file" class="img_file" />

    <br></br>

    <input type="submit" value="Upload the Image" />


    </form>

beforeSend函數中,我使用return false來防止表單自身提交。 但這是行不通的。 我該如何實現?

在您的html中刪除javascript:void(0)並放入#代替,並使用event.preventDefault(); 您觸發提交的位置。 像這樣:

$(document).on('click', '#submitname', function (event) {
 event.preventDefault();
  $.ajax({
    url: 'somepage.php',
    type: 'post',
    dataType:'html',   
    data: $('#formname').serialize(),
    success: function(response, textStatus, jqXHR){

     ///Do something

},
   error: function(jqXHR, textStatus, errorThrown){
      console.log('error(s):'+textStatus, errorThrown);
   }
 });
});

要中止當前的“運行中”請求,您需要中止;)在beforeSend回調中,第一個參數是jqXHR對象:

beforeSend: function(jqXHR) {
    //some other code to check if we need to abort current request, if so...
    jqXHR.abort();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM