XMLHttpRequest 获取response的数据
时间: 2024-06-13 22:09:46 浏览: 9
XMLHttpRequest是一种在后台与服务器交换数据的技术。它可以在不重新加载整个页面的情况下更新页面的局部内容。获取response的数据有以下几种方法:
1.使用responseText属性获取文本数据:
```javascript
var xhr = new XMLHttpRequest();
xhr.open('GET', 'example.php', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send();
```
2.使用responseXML属性获取XML数据:
```javascript
var xhr = new XMLHttpRequest();
xhr.open('GET', 'example.xml', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseXML);
}
};
xhr.send();
```
3.使用responseType属性获取二进制数据:
```javascript
var xhr = new XMLHttpRequest();
xhr.open('GET', 'example.bin', true);
xhr.responseType = 'arraybuffer';
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.response);
}
};
xhr.send();
```
4.使用Blob和FileReader对象获取二进制数据:
```javascript
var xhr = new XMLHttpRequest();
xhr.open('GET', 'example.bin', true);
xhr.responseType = 'blob';
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var blob = xhr.response;
var reader = new FileReader();
reader.onload = function() {
console.log(reader.result);
};
reader.readAsText(blob);
}
};
xhr.send();
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)