본문 바로가기
WEB

[JavaScript/PHP] Ajax로 PHP에서 배열받아오기

by 겅아링 2020. 9. 10.
반응형

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로 변환

반응형

'WEB' 카테고리의 다른 글

[HTTP:웹 기본 지식] 인터넷 통신  (0) 2021.02.19
[HTML/CSS/JavaScript] 회원가입 폼 + 정규식  (0) 2020.08.16