//THIS AJAX CODE WORKING GREAT.
$(document).ready(function(e) {
$("#ajaxupload").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "http://example.com/upload",
type: "POST",
data: new FormData(this),
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
success: function(data){
//if success. Response is HTML. data = html. insert to my .result-wrapper.
$(".result-wrapper").prepend(data);
},
error: function(){
console.log('there\'s error!')
}
});
}));
});
如何轉換Ajax Jquery爲純Javascript?我試着找到圍繞Stackoverflow的解決方案,然後嘗試通過答案實現代碼標記爲接受仍然錯誤,我的後端控制器沒有檢測到數據輸入值..轉換Ajax提交表單,然後獲得HTML回覆純Javascript使用
上面的ajax代碼。 1. Sumbit並獲得響應,無需刷新頁面。
迴應是HTML。
無需設置數據。因爲數據已經在我的HTML表單中設置。
表單有多個輸入文件上傳和多個輸入名稱。所以輸入的長度不是一個靜態數字,取決於文件。
如何使用javascript實現它?無需刷新即可提交,獲得回覆,然後可以提交填寫HTML的數據?
我試着用下面的代碼來做到這一點。
document.getElementById('ajaxupload').addEventListener('submit', function(e) {
e.preventDefault();
//e.submit();
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://example.com/upload/', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
// do something to response
console.log(this.responseText);
};
//xhr.send();
xhr.send(document.getElementById('ajaxupload').innerHTML); //my form id = ajaxupload
});
HTML:
<form action="http://example.com/upload" id="ajaxupload" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<input id="insert-file" name="usr_files[]" type="file" multiple="">
<!--other input will generate inside this form on change `insert-file` .. depend on how many length file selected. ex if 2 files selected:
<input class="custom-file-name" name="usr_files[text][0]" type="text" value="My custom file name" required/>
<input class="custom-file-name" name="usr_files[text][1]" type="text" value="My custom file name no.2" required/> -->
</form>
爲什麼你認爲發送表單的整個HTML在發送FormData對象的地方几乎是相同的?僅供參考:'XMLHttpRequest'支持FormData *(在現代瀏覽器)* – adeneo
所以這意味着我的JavaScript代碼以上將工作,如果我設置數據?如何使用多個文件選擇來實現它? –
'xhr.send(document.getElementById('ajaxupload')。innerHTML)'wat –