2016-06-15 37 views
3

我想創建一個表單,允許用戶填寫數據,如果選項被選中,div打開並且用戶可以選擇上傳文件以及他們的提交。如何通過AJAX和jQuery傳遞文件數據?

我遇到的問題是如何將文件直通AJAX正確。我無法正確地將它網格化在一起,以獲得我正在查找的結果,這是發佈到我的PHP腳本的文件。這裏是我的傳遞數據代碼:

$(document).ready(function() { 
$("#submit_btn").click(function() { 

    var proceed = true; 
    //simple validation at client's end 
    //loop through each field and we simply change border color to red for invalid fields  
    $("#contact_form input[required=true], #contact_form textarea[required=true]").each(function(){ 
     $(this).css('border-color',''); 
     if(!$.trim($(this).val())){ //if this field is empty 
      $(this).css('border-color','red'); //change border color to red 
      proceed = false; //set do not proceed flag 
     } 
     //check invalid email 
     var email_reg = /^([\w-\.][email protected]([\w-]+\.)+[\w-]{2,4})?$/; 
     if($(this).attr("type")=="email" && !email_reg.test($.trim($(this).val()))){ 
      $(this).css('border-color','red'); //change border color to red 
      proceed = false; //set do not proceed flag    
     } 
    }); 

    if(proceed) //everything looks good! proceed... 
    { 
     //get input field values data to be sent to server 

     var search_array = $('input[name="donation"]').map(function(){ 
       return $(this).val(); 
     }).get(); 

     post_data = { 
      'user_name'  : $('input[name=full_name]').val(), 
      'user_email' : $('input[name=email]').val(), 
      'address' : $('input[name=address]').val(), 
      'address2' : $('input[name=address2]').val(), 
      'city' : $('input[name=city]').val(), 
      'state' : $('input[name=state]').val(), 
      'zip' : $('input[name=zip]').val(), 
      'ccnum' : $('input[name=ccnum]').val(), 
      'expmonth' : $('select[name=expmonth]').val(), 
      'expyear' : $('select[name=expyear]').val(), 
      'cardname' : $('input[name=cardname]').val(), 
      'ccvcode' : $('input[name=ccvcode]').val(), 
      'donation' : $('input[name=donation]:checked').val(), 
      'donation_other' : $('input[name=donation_other]').val(), 
      'contact_phone' : $('input[name=contact_phone]').val(), 
      'attached_file' : $('input[name=attached_file]').val(), 
      'donatecomments' : $('textarea[name=donatecomments]').val() 
     }; 





     //Ajax post data to server 
     $.post('https://www.xxxxxx.org/catch.php', post_data, function(response){ 
      if(response.type == 'error'){ //load json data from server and output message  
       output = '<div class="error">'+response.text+'</div>'; 
      }else{ 


       output = '<div class="success">'+response.text+'</div>'; 
       //reset values in all input fields 
       $("#contact_form input[required=true], #contact_form textarea[required=true]").val(''); 
       $("#contact_form #contact_body").slideUp(); //hide form after success 
       window.top.location.href = "https://www.xxxxxxxxx.org/thank-you"; 
      } 
      $("#contact_form #contact_results").hide().html(output).slideDown(); 
     }, 'json'); 
    } 
}); 

//reset previously set border colors and hide all message on .keyup() 
$("#contact_form input[required=true], #contact_form textarea[required=true]").keyup(function() { 
    $(this).css('border-color',''); 
    $("#result").slideUp(); 
}); 
}); 

而且我的文件選擇行:

<input id="attached_file" name="attached_file" style="width:220px;" placeholder="Enter an amount - No $ sign" type="file" value="" onfocus="jQuery(this).prev(&quot;input&quot;).attr(&quot;checked&quot;, true); if(jQuery(this).val() == &quot;Other&quot;) { jQuery(this).val(&quot;&quot;); }" onblur="if(jQuery(this).val().replace(&quot; &quot;, &quot;&quot;) == &quot;&quot;) { jQuery(this).val(&quot;Other&quot;); }" tabindex="18"> 

我怎樣才能得到實際的文件數據傳遞呢?

+0

你需要把它作爲FORMDATA。我會做一個例子。 – mwilson

+0

@mwilson - 謝謝!我無法完全弄清楚。其他示例採用與此不同的路線。 – MrTechie

回答

3

您需要將文件存儲爲FormData。您仍然可以通過將表單數據附加到FormData對象來將表單數據與您的文件附件一起發送。請參閱下面的示例:

注意:本示例假定它是一個xml文件。如果它不是xml文件,請不要使用xml部分(if語句中的最後3行)。

的JavaScript

// #fileUpload is to a input element of the type file 
var file = $('#fileUpload')[0].files[0] 
var fd = new FormData(); 
fd.append('theFile', file); 
$.ajax({ 
    url: '...', 
    type: 'POST', 
    processData: false, 
    contentType: false, 
    data: fd, 
    success: function (data, status, jqxhr) { 
     //success code 
    }, 
    error: function (jqxhr, status, msg) { 
     //error code 
    } 
}); 

C#

protected void Page_Load(object sender, EventArgs e) 
{   
    try 
    { 
     foreach (string file in Request.Files) 
     { 
      var fileContent = Request.Files[file]; 
      if (fileContent != null && fileContent.ContentLength > 0) 
      { 
       Stream stream = fileContent.InputStream; 
       BinaryReader br = new BinaryReader(stream); 
       byte[] binaryData = br.ReadBytes(fileContent.ContentLength); 
       string xml = System.Text.Encoding.Default.GetString(binaryData); 
       XmlDocument xmlDoc = new XmlDocument(); 
       xmlDoc.LoadXml(xml); 
      } 
     } 
    } 
    catch (Exception ex) 
    { 

    } 
} 
0

,你可以做到這一點使用FORMDATA。試試這個

$("form#data").submit(function() { 

    var formData = new FormData($(this)[0]); 

    $.post($(this).attr("action"), formData, function(data) { 
     alert(data); 
    }); 

    return false; 
}); 

// HTML 
<form id="data" method="post" enctype="multipart/form-data"> 
    <input type="text" name="first" value="Bob" /> 
    <input type="text" name="middle" value="James" /> 
    <input type="text" name="last" value="Smith" /> 
    <input name="image" type="file" /> 
    <button>Submit</button> 
</form> 
0

有兩種方法可以做到這一點,一個是傳遞參數,如果你對你形成少變量..

$post('url',{param1:$("#name").val(),param2:$("#middle").val()},function(data){ 
//Action as per data returned from php code 
}); 

另一種方法是序列化()方法。

$post('url',{param1:$("form").serialize()},function(data){ 
//Action as per data returned from php code 
}); 
0
var formData = new FormData($("#formid")[0]); 

$.ajax({ 
    url:'url', 
    type: 'POST', 
    data: formData, 
    processData: false, 
    contentType: false, 
    async: false, 
    success:function(response){ 
     if(response == '100'){ 
      swal({ 
       title: "Blog Added", 
       text: "Blog Added Successfully", 
       type: "success", 
       confirmButtonText: "OK", 
       showCancelButton: false, 
      }, function(){ 
       /*location.reload();*/ 
       window.location.href = 'redirect link'; 
      }); 
     }else{ 
      toastr.error(response); 
     } 
    } 
});