//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代码。 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>
答案 0 :(得分:1)
在本机代码中使用相同的formdata对象
document.getElementById('ajaxupload').addEventListener('submit', function(e) {
e.preventDefault();
var formData = new FormData(this);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://example.com/upload/');
xhr.onreadystatechange = function() {
if ( xhr.readyState === 4 && xhr.status === 200 ) {
console.log( xhr.responseText );
}
}
xhr.send( formData ); //my form id = ajaxupload
});
答案 1 :(得分:-1)
function ajaxGet(url, cb, token){
var ajaxReq = new XMLHttpRequest();
ajaxReq.addEventListener('load',function(){
if(ajaxReq.status === 200)cb(null,{responseText:ajaxReq.responseText,rawAjaxRequest:ajaxReq});
else cb({statusCode:ajaxReq.status,rawAjaxRequest:ajaxReq},null);
});
ajaxReq.addEventListener('error',function(data){
console.dir(数据);
var err = new Error('ajaxGet期间发生致命错误,请参阅控制台以获取更多信息');
err.name ='XMLHttpRequestError';
cb(错误,空);
});
ajaxReq.open('GET',url,true);
如果(令牌){
ajaxReq.setRequestHeader('Authorization',token);
}
ajaxReq.send();
},