JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写,也易于机器解析和生成。在现代JavaScript中,有多种方法可以在不使用jQuery的情况下获取和处理JSON数据。
Fetch API是现代浏览器提供的原生API,用于替代传统的XMLHttpRequest。
// 获取JSON数据
fetch('https://api.example.com/data.json')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
console.log(data); // 处理JSON数据
// 使用数据...
})
.catch(error => {
console.error('There was a problem with the fetch operation:', error);
});
这是传统的AJAX请求方式,虽然较老但仍然可用。
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data.json', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var data = JSON.parse(xhr.responseText);
console.log(data); // 处理JSON数据
// 使用数据...
} else {
console.error('Request failed. Returned status of ' + xhr.status);
}
}
};
xhr.send();
结合Fetch API和async/await可以使代码更简洁。
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data.json');
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
console.log(data); // 处理JSON数据
// 使用数据...
} catch (error) {
console.error('There was a problem fetching the data:', error);
}
}
fetchData();
const jsonString = '{"name":"John", "age":30, "city":"New York"}';
const obj = JSON.parse(jsonString);
console.log(obj.name); // 输出: John
const obj = {name: "John", age: 30, city: "New York"};
const jsonString = JSON.stringify(obj);
console.log(jsonString); // 输出: {"name":"John","age":30,"city":"New York"}
原因:浏览器同源策略限制
解决方案:
原因:JSON格式不正确
解决方案:
try {
const data = JSON.parse(jsonString);
} catch (e) {
console.error('Invalid JSON:', e);
}
fetch('https://api.example.com/data.json')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.catch(error => {
console.error('Fetch error:', error);
// 显示用户友好的错误信息
});
现代JavaScript已经提供了强大且易用的原生API来处理JSON数据,无需依赖jQuery等库。
没有搜到相关的沙龙