WEB
[JavaScript/PHP] Ajax로 PHP에서 배열받아오기
겅아링
2020. 9. 10. 15:12
반응형
html이 로드되면 AJAX로 php에서 데이터 가져오기!
JavasScript에서 배열을 받을때
jQuery.parseJSON(data)
: JSON을 js 객체로 변환
//js
$(function () {
$.ajax({
type : 'POST',
url : 'mysql_test.php',
success: function (data) {
const result = jQuery.parseJSON(data);
let str = `<table border="1">
<tr>
<th colspan="2">nameTBL</th>
</tr>
<tr>
<th>id</th><th>name</th>
</tr>`;
for (let i = 0; i < result.length; i++) {
str += `<tr>
<td> ${result[i].id} </td><td> ${result[i].name} </td>
</tr>`;
}
str += '</table>';
$("body").html(str);
}
}
)
})
php에서 배열을 보낼때
json_encode(배열)
: array를 JSON으로 변환
<?php
try {
$conn = new PDO('mysql:host=localhost;dbname=testdb', 'root', '111111');
$query = "select * from testtbl";
$stmt = $conn->prepare($query);
$stmt->execute();
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($row);
} catch (PDOException $e) {
echo $e->getMessage();
}
json_decode();
: JSON을 array로 변환
반응형