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

时间:2014-03-10 12:19:39

标签: php jquery forms jquery-forms-plugin

我正在使用jQuery form plugin上传文件并显示进度条。

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来阻止表单提交自己。但它不起作用。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:0)

在你的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);
   }
 });
});

答案 1 :(得分:0)

要中止当前'in run'请求,你需要中止它;)在beforeSend回调中,第一个参数是jqXHR对象:

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