2017-04-23 17 views
0

我在一個頁面上有兩種形式,一種是上傳文件的形式,另一種是彈出式窗口,當文件上傳時詢問電子郵件。兩者都使用ajax,我在處理它們時遇到了一些麻煩。是否有可能在頁面中調用Ajax中有兩個頁面的表單?

我想我的每個ajax代碼只能在他們各自的表單上工作,而不是在我的html頁面上找到的第一個表單(現在只有最高的<form></form>由我的ajax代碼執行)。

AJAX:

# for uploading files form 
    $("#fileupload").fileupload({ 
    dataType: 'json', 
    sequentialUploads: true, 
    start: function (e) { 
     $("#modal-progress").modal("show"); 
    }, 
    ... 
    done: function (e, data) { 
     if (data.result.is_valid) { 
     ... 
     } 
    } 
    }); 

# for email form 
$(document).on('submit', '#formTwo', function(e){ 
    e.preventDefault(); 

    $.ajax({ 
     # is there a command to specify in which form it should run ? 
     type:'POST', 
     url:'/tools/newsletter/', 
     data:{ 
      email:$('#email').val(), 
      csrfmiddlewaretoken:$('#formTwo input[name=csrfmiddlewaretoken]').val(), 
     }, 
    }); 

    $("#modal-progress").modal("hide"); 
}); 

forms.html

<!-- Email form --> 
<form id="formTwo" method="post" action="newsletter"> 
    ... 
    <input id="email" maxlength="255" placeholder="Votre adresse email" name="email" type="text" class="form-control"> 
    <input type="submit" class="btn btn-success"> 
</form> 


<!-- Uploading files form --> 
<form id="formOne" method="post" enctype="multipart/form-data" action="{% url 'basic_upload' %}"> 
... 
<input id="fileupload" type="file" name="file" multiple> 
</form> 

我怎樣才能解決這個問題?

+0

你的第一個形式不正常關閉,它缺少了'/'形式的前面的結束標記。 – Pango

+0

@Pango只是從stackoverflow上編輯錯誤,已更正。 – Lindow

回答

1

可以使用$(this).is(selector)if語句來驗證你處理什麼樣的形式,像

$(document).on('submit', '#formTwo, #formOne', function(e){ 
    e.preventDefault(); 

    if($(this).is('#formTwo')) { 
     $.ajax({ 
      type:'POST', 
      url:'/tools/newsletter/', 
      data: { 
       email:$('#email').val(), 
       csrfmiddlewaretoken:$('#formTwo input[name=csrfmiddlewaretoken]').val(), 
      }, 
     }); 
    } else if ($(this).is('#formOne')) { 
     // formOne code 
    } 

    $("#modal-progress").modal("hide"); 
}); 
相關問題