vue2之XMLHttpRequest原生请求 与 前端发起XML请求,校验下载文件是否可下载
vue2之前端发起XML请求,校验下载文件是否可下载
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
var timeStart = '';
var timeEnd = '';
var time = new Date().getTime();
xhr.addEventListener('readystatechange', function() {
if (this.readyState == 1) {
timeStart = new Date().getTime();
}
if (this.readyState === 4) {
timeEnd = new Date().getTime();
if (timeEnd - timeStart < 3000) {
that.downloadIP = ip;
} else {
console.log('不可下载', i);
}
}
});
xhr.open('GET', `https://${ip}:8092/curl?t=` + time);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send('');
XML发起post请求 json格式
var xhr = new XMLHttpRequest();
var url = "http://example.com/api";
var data = {name: "张三", age: 20};
var json = JSON.stringify(data);
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send(json);
XML发起post请求 formData格式
var xhr = new XMLHttpRequest();
var url = "http://example.com/api";
var data = new FormData();
data.append("name", "张三");
data.append("age", 20);
xhr.open("POST", url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send(data);
var xhr = new XMLHttpRequest();
var url = "http://example.com/api";
var params = "name=张三&age=20";
var data = new FormData();
params.split("&").forEach(function(param) {
var parts = param.split("=");
data.append(parts[0], decodeURIComponent(parts[1]));
});
xhr.open("POST", url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send(data);
```
## XML发起get请求
```js
var xhr = new XMLHttpRequest();
var url = "http://example.com/api?name=张三&age=20";
xhr.open("GET", url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send();
```