문제는 자주 발생하므로 data
은 대부분의 사람들이 생각하는 것이 아닙니다. data
은 이 아니고은 data-*
속성의 접근 자이며 그 이상이고 그보다 작습니다. 그것은 요소에 대한 jQuery의 내부 데이터 캐시를 관리합니다. 은 특성의 캐시를으로 초기화하지만 캐시의 데이터를 복제하고 데이터를 처리하며 결코 특성에 다시 쓰지 않습니다.
data
은 당신이 읽고있는 내용이 JSON이고 자동으로 을 구문 분석합니다. 따라서 객체를 가져오고 파싱 할 필요가 없습니다. 그래서 data
를 사용
는
:
var locations = $("#locations-json").data("json");
console.log(locations);
console.log("There are " + locations.cities.length + " cities");
<div id="locations-json" data-json="{"cities": "[1, 2, 3, 4]", "airports": "[5, 6]"}" style="display: none"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
당신은 12 개 도시가 말한다 댓글에서 언급 한 바와 같이.
{"cities": [1, 2, 3, 4], "airports": [5, 6]}
예 :
var locations = $("#locations-json").data("json");
console.log(locations);
console.log("There are " + locations.cities.length + " cities");
<div id="locations-json" data-json="{"cities": [1, 2, 3, 4], "airports": [5, 6]}" style="display: none"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
당신은 아마가되도록 JSON을 의미
{"cities": "[1, 2, 3, 4]", "airports": "[5, 6]"}
다음 JSON은 cities
(그리고 airports
)는 문자열 값을 제공하기 때문이다 당신이 data
의 다양한 기능을 필요로하지 않는 1,363,210
하지만, 단지 자신을 attr
를 사용하여 구문 분석 :
var locations = JSON.parse($("#locations-json").attr("data-json"));
console.log(locations);
console.log("There are " + locations.cities.length + " cities");
<div id="locations-json" data-json="{"cities": [1, 2, 3, 4], "airports": [5, 6]}" style="display: none"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
참고 :
으로 this edit의 질문 이처럼 보이는 div
이 유효합니다. :
<div id="locations-json" data-json="{"cities": "[1, 2, 3, 4]", "airports": "[5, 6]"}" style="display: none"></div>
그러나 you edited it again이 잘못되는, 다음과 같이합니다 : "
와
<div id="locations-json" data-json="{"cities": "[1, 2, 3, 4]", "airports": "[5, 6]"}" style="display: none"></div>
버전이 올바른지, 그것을 사용하십시오.
JSON 개체에는 따옴표가있는 키가 있어야합니다. '{ "cities": "[1, 2, 3, 4]", "airports": "[5, 6]"}' – Frxstrem
[ JSON] (http://stackoverflow.com/questions/11338774/serialize-form-data-to-json) – SAM
@TJCrowder 질문의 맨 아래에 요소를 추가했습니다. –