疯狂前端面试题(四)

一、Ajax、JSONP、JSON、Fetch 和 Axios 技术详解

1. Ajax(异步 JavaScript 和 XML)

什么是 Ajax?
Ajax 是一种用于在不刷新页面的情况下与服务器进行数据交互的技术。它通过 `XMLHttpRequest` 对象实现。

优点
- 支持同步和异步请求。
- 能够发送和接收多种格式的数据(如 JSON、XML 等)。

缺点
- 原生代码较复杂。
- 不支持跨域请求(需要服务器配置 CORS 或使用 JSONP)。

示例
// 创建 XMLHttpRequest 对象
const xhr = new XMLHttpRequest();

// 配置请求
xhr.open('GET', 'https://api.example.com/data', true);

// 设置响应类型
xhr.responseType = 'json';

// 处理响应
xhr.onload = function () {
  if (xhr.status === 200) {
    console.log(xhr.response); // 输出返回的 JSON 数据
  } else {
    console.error('Error:', xhr.status);
  }
};

// 发送请求
xhr.send();

2. JSONP(JSON with Padding)

什么是 JSONP?
JSONP 是一种绕过浏览器同源策略的方法,通过 `

3. JSON(JavaScript Object Notation)

什么是 JSON?
JSON 是一种轻量级的数据交换格式,易于阅读和编写,也易于机器解析和生成。

用途
- 作为前后端交互的数据格式。
- 可以通过 `JSON.parse()` 将字符串转换为对象,通过 `JSON.stringify()` 将对象转换为字符串。

示例

// JSON 字符串
const jsonString = '{"name": "Alice", "age": 25}';

// 转换为对象
const obj = JSON.parse(jsonString);
console.log(obj.name); // 输出: Alice

// 转换回 JSON 字符串
const str = JSON.stringify(obj);
console.log(str); // 输出: {"name":"Alice","age":25}

4. Fetch API

什么是 Fetch?
Fetch 是现代浏览器提供的一个更简洁、强大的接口,用于发起网络请求。它基于 Promise 设计,支持链式调用。

优点
- 更现代化,基于 Promise。
- 支持多种 HTTP 方法(GET、POST 等)。
- 自动解析响应为 JSON。

缺点
- 不支持 IE 浏览器。
- 错误处理需要手动检查状态码。

示例

fetch('https://api.example.com/data', {
  method: 'GET', // 请求方法
  headers: { 'Content-Type': 'application/json' }, // 请求头
})
  .then(response => {
    if (!response.ok) throw new Error('Network response was not ok');
    return response.json(); // 解析为 JSON
  })
  .then(data => console.log(data)) // 处理数据
  .catch(error => console.error('Error:', error)); // 捕获错误

5. Axios

什么是 Axios?
Axios 是一个基于 Promise 的 HTTP 客户端,可以用于浏览器和 Node.js。它提供了比 Fetch 更丰富的功能。

优点
- 支持自动转换 JSON 数据。
- 内置拦截器,便于请求和响应的预处理。
- 支持取消请求。
- 兼容所有主流浏览器。

缺点
- 需要额外引入库。

示例

// 安装 Axios
// npm install axios

import axios from 'axios';

// 发起 GET 请求
axios.get('https://api.example.com/data')
  .then(response => {
    console.log(response.data); // 输出返回的数据
  })
  .catch(error => {
    console.error('Error:', error);
  });

// 发起 POST 请求
axios.post('https://api.example.com/data', {
  name: 'Alice',
  age: 25,
})
  .then(response => console.log(response.data))
  .catch(error => console.error('Error:', error));

跨域问题及解决方案

1. 同源策略
浏览器的安全机制限制了不同源(协议、域名、端口)之间的直接通信。

2. 解决方案
- **CORS(跨域资源共享)**:
  - 服务器通过设置响应头(如 `Access-Control-Allow-Origin`)允许特定来源访问资源。
  - 支持所有 HTTP 方法。
  
- **JSONP**:
  - 使用 `

你可能感兴趣的:(前端,html5,ajax,正则表达式,javascript,firefox,chrome)