MySQL 데이터의 JSON 텍스트를 생성하는 PHP 파일이 있습니다.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<title>Sample Page</title>
<script>
var settings = {
"async": true,
"crossDomain": true,
"url": "http://www.hotel1.com/Experiment/Api/Json1.php?ID=1",
"method": "GET"
}
$.ajax(settings).done(function (response) {
console.log(response);
console.log(response.something.something)
});
</script>
위에서 내 코드를 볼 수 있습니다.
[
{
"Worker1": {
"ID :": "1",
"Username": "Tony"
}
}
]
위에서 인쇄중인 내 JSON 텍스트를 볼 수 있습니다. 내 문제는 JavaScript의 JSON 텍스트에서 ID를 선택하는 방법을 알고 싶습니다. 위와 같이. response.Worker1.ID라고 말하려고하면 ID가 정의되지 않았다는 오류가 표시됩니다.
누군가 내 실수를 고칠 수 있습니까?
JSON을 javascript 객체로 구문 분석해야합니다. JSON.parse()
다음과 같이을 사용하십시오 .
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<title>Sample Page</title>
<script>
var settings = {
"async": true,
"crossDomain": true,
"url": "http://www.hotel1.com/Experiment/Api/Json1.php?ID=1",
"method": "GET"
}
$.ajax(settings).done(function (response) {
response = JSON.parse(response); // the change is here
console.log(response);
console.log(response.something.something)
});
</script>
또한 "sample json"은 배열을 반환하므로 대괄호 []
. 따라서 액세스하려면 response[0].something
.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다