
JS
JS
const JSonString = '{"name": "Tom", "age": 25}';

Java
console.log(JSonObj.name); // Tom
console.log(JSonObj.age); // 25
2. 使用JSON.stringify()方法将Javascript对象转化为JSON字符串。
JS
const JSonObj = {name: "Tom", age: 25};
const JSonString = JSON.stringify(JSonObj);
console.log(JSonString); // {"name":"Tom","age":25}
3. 使用XMLHttpRequest获取JSON数据并解析。
JS
const xhr = new XMLHttpRequest();
xhr.open('GET', 'url/to/JSon', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
const JSonResponse = JSON.parse(xhr.responseText);
console.log(JSonResponse);
} else {
console.log('Error: ' + xhr.statusText);
}
}
};
xhr.send();
4.使用fetch方法获取JSON数据并解析。
JS
fetch('url/to/JSon')
.then(response => response.JSon())
.then(data => {
console.log(data);
})
.catch(error => {
console.log('Error: ' + error);
});
Copyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号