//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 –