JSON 的常见用途是与 Web 服务器交换数据。
从 Web 服务器接收数据时,数据始终是字符串。
使用 JSON.parse()
解析数据,数据变成 JavaScript 对象。
如果您有数据存储在 JavaScript 对象中,则可以转换该对象 转换为 JSON,并将其发送到服务器:
const myObj = {name: "John",
age: 31, city: "New York"};
const myJSON =
JSON.stringify(myObj);
window.location = "demo_json.php?x=" + myJSON;
自己尝试一下 →
<!DOCTYPE html>
<html>
<body>
<h2>Convert a JavaScript object into a JSON string, and send it to the server.</h2>
<script>
const myObj = { name: "John", age: 31, city: "New York" };
const myJSON = JSON.stringify(myObj);
window.location = "demo_json.php?x=" + myJSON;
</script>
</body>
</html>
如果您收到 JSON 格式的数据,您可以轻松地将其转换为 JavaScript 目的:
const myJSON =
'{"name":"John",
"age":31, "city":"New York"}';
const myObj =
JSON.parse(myJSON);
document.getElementById("demo").innerHTML = myObj.name;
自己尝试一下 →
<!DOCTYPE html>
<html>
<body>
<h2>Convert a JSON string into a JavaScript object.</h2>
<p id="demo"></p>
<script>
const myJSON = '{"name":"John", "age":31, "city":"New York"}';
const myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = myObj.name;
</script>
</body>
</html>
您可以使用 AJAX 请求从服务器请求 JSON
只要将服务器的响应写成JSON格式,就可以 将字符串解析为 JavaScript 对象。
使用 XMLHttpRequest 从服务器获取数据:
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
const myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.name;
};
xmlhttp.open("GET", "json_demo.txt");
xmlhttp.send();
自己尝试一下 →
<!DOCTYPE html>
<html>
<body>
<h2>Fetch a JSON file with XMLHttpRequest</h2>
<p id="demo"></p>
<script>
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
const myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.name;
}
xmlhttp.open("GET", "json_demo.txt");
xmlhttp.send();
</script>
</body>
</html>
看一下 json_demo.txt:https://basicit.org/js/json_demo.txt
当对从数组派生的 JSON 使用 JSON.parse()
时,该方法将 返回 JavaScript 数组,而不是 JavaScript 对象。
从服务器以数组形式返回的 JSON:
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
const myArr = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myArr[0];
}
}
xmlhttp.open("GET", "json_demo_array.txt", true);
xmlhttp.send();
自己尝试一下 →
<!DOCTYPE html>
<html>
<body>
<h2>Fetch a JSON file with XMLHttpRequest</h2>
<p>Content written as an JSON array will be converted into a JavaScript array.</p>
<p id="demo"></p>
<script>
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
const myArr = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myArr[0];
}
xmlhttp.open("GET", "json_demo_array.txt", true);
xmlhttp.send();
</script>
</body>
</html>
看一下 json_demo_array.txt:https://basicit.org/js/json_demo_array.txt