这是我编写的一个函数,它总是用于 ajax 请求、帖子...随便
function ajax(a,b,e,d,f,g,c){
// url,callback,type(get),FormData(null),uploadProgress,progress
c=new XMLHttpRequest;
!f||(c.upload.onprogress=f);
!g||(c.onprogress=g);
c.onload=b;
c.open(e||'get',a);
c.send(d||null)
}
我认为只有 chrome 支持 responseType='json';
通过删除responseType='json';,您可以使用
JSON.parse()
所以:
JSON.parse(oReq.response)
要从这个 ajax 调用中获得响应,您可以选择 3 种方式
1.在我/或你的情况下
c.response
//your
oReq.response
2.使用这个
this.response // i always use this.
3.e.target
e.target.response
ajax函数说明:
这个ajax函数有6个可用参数
url, callback, type(get or post),FormData(or null),uploadProgress,progress
只需要 2 个 url 和 callback(简单获取请求)
ajax('url',function(){console.log(this.response)})
// it's better to use a function reference to avoid memory leaks
// like
function cb(){console.log(this.response)};
ajax('url',cb)
在你的情况下,你使用 post
所以你需要 4 个参数
url、callback、type(post in your case) 和 formdata
所以:
ajax('url',callbackFunction,'post',fd);
fd 有两种构建方式
var fd=new FormData();
fd.append('key','value');
ajax('url',callbackFunction,'post',fd);
或者你也可以发布整个表格
var fd=new FormData(document.getElementsByTagName('form')[0]);
ajax('url',callbackFunction,'post',fd);
您也可以添加进度事件功能
function progress(e){
console.log(e.loaded/e.total*100)
}
上传进度相同
回调函数就是这样的
function callbackFunction(e){
console.log(e.target.response);
console.log(this.response);
console.log(c.response);
// without the reponsetype
console.log(JSON.parse(e.target.response));
console.log(JSON.parse(this.response));
console.log(JSON.parse(c.response))
}
如果您有任何问题,请尽管提出。