Servidor JSON

JSON 的一个常见用途是与 Web 服务器交换数据。

从 Web 服务器接收数据时,数据始终是字符串。

JSON.parse() 解析数据,数据会成为 JavaScript 对象。

发送 Data

如果您将数据存储在 JavaScript 对象中,则可以将对象转换为 JSON,并将其发送到服务器:

Ejemplo

const myObj = {name: "Bill", age: 31, city: "New York"};
const myJSON = JSON.stringify(myObj);
window.location = "demo_json.php?x=" + myJSON;

Intente hacerlo usted mismo

接收 Data

如果您接收 JSON 格式的数据,则可以轻松地将其转换为 JavaScript 对象:

Ejemplo

const myJSON = '{"name":"Bill", "age":31, "city":"New York"}';
const myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = myObj.name;

Intente hacerlo usted mismo

来自服务器的 JSON

您可以使用 AJAX 请求从服务器请求 JSON

只要来自服务器的响应以 JSON 格式编写,您就可以将字符串解析为 JavaScript 对象。

Ejemplo

使用 XMLHttpRequest 从服务器获取数据:

const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
  const myObj = JSON.parse(this.responseText);
  document.getElementById("demo").innerHTML = myObj.name;
};
xmlhttp.open("GET", "json.txt");
xmlhttp.send();

Intente hacerlo usted mismo

Vea también:json.txt

JSON en forma de array

Al usar JSON.parse() Este método devolverá un array de JavaScript en lugar de un objeto de JavaScript.

Ejemplo

De vuelta del servidor en forma de array JSON:

const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
  const myArr = JSON.parse(this.responseText);
  document.getElementById("demo").innerHTML = myArr[0];
  }
}
xmlhttp.open("GET", "json_array.txt", true);
xmlhttp.send();

Intente hacerlo usted mismo

Vea también:json_array.txt