JSON 서버
JSON의 일반적인 용도는 웹 서버와 데이터 교환입니다。
웹 서버에서 데이터를 받을 때, 데이터는 항상 문자열입니다。
용 JSON.parse()
데이터를 분석하면 데이터가 JavaScript 객체가 됩니다。
데이터 전송
데이터를 JavaScript 객체에 저장하면 객체를 JSON으로 변환하여 서버로 전송할 수 있습니다:
예제
const myObj = {name: "Bill", age: 31, city: "New York"}; const myJSON = JSON.stringify(myObj); window.location = "demo_json.php?x=" + myJSON;
데이터 수신
JSON 형식의 데이터를 받으면 JavaScript 객체로 쉽게 변환할 수 있습니다:
예제
const myJSON = '{"name":"Bill", "age":31, "city":"New York"}'; const myObj = JSON.parse(myJSON); document.getElementById("demo").innerHTML = myObj.name;
서버에서 온 JSON
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.txt"); xmlhttp.send();
참조하십시오:json.txt
배열 JSON
배열 형식의 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_array.txt", true); xmlhttp.send();
참조하십시오:json_array.txt