댓글 검색 목록

[기타] JavaScript, JSON 및 PHP를 사용한 AJAX CRUD 자습서 – 단계별 가이드!

페이지 정보

작성자 운영자 작성일 20-12-21 16:32 조회 685 댓글 0

오늘은 AJAX CRUD Tutorial을 사용하여 레코드를 생성 또는 삽입, 읽기, 업데이트 및 삭제하는 방법을 배우겠습니다. jQuery, JSON 및 PHP를 사용합니다.


이 자습서의 내용은 다음과 같습니다.


1.0 튜토리얼 개요

2.0 프로그램 출력 1

3.0 REST API 설정


4.0 기본 파일 및 폴더 

4.1 파일 구조

4.2 index.html 파일 생성

4.3 부트 스트랩 활성화

4.4 사용자 지정 CSS 파일 만들기

4.5 jQuery 라이브러리 및 Bootbox 다운로드

4.6 app.js 파일 생성

4.7 "제품"스크립트 생성

4.8 출력


5.0 jQuery AJAX를 사용하여 JSON 데이터를 읽는 방법? 

5.1 첫 페이지 로드시 제품 표시

5.2 버튼 클릭시 제품 표시

5.3 showProducts() 함수 생성

5.4 제품 목록 가져 오기

5.5 "제품 생성"버튼 추가

5.6 HTML 테이블 작성

5.7 레코드 당 테이블 행 작성

5.8 페이지 콘텐츠에 삽입

5.9 페이지 제목 변경

5.10 출력


6.0 jQuery AJAX를 사용하여 데이터를 생성하거나 삽입하는 방법? 

6.1 "제품 생성"버튼 클릭 처리

6.2 API에서 카테고리 목록 가져 오기

6.3 "카테고리 옵션"선택 필드 작성

6.4 "제품 읽기"버튼 추가

6.5 "제품 생성"HTML 양식 작성

6.6 "제품 생성"양식 표시 및 페이지 제목 변경

6.7 "제품 생성"양식 제출 처리

6.8 양식 데이터 가져 오기

6.9 서버로 데이터 보내기

6.10 출력


7.0 jQuery AJAX를 사용하여 하나의 데이터를 읽는 방법? 

7.1 "읽기"버튼 클릭 처리

7.2 제품 ID 얻기

7.3 API에서 하나의 레코드 읽기

7.4 "제품 읽기"버튼 추가

7.5 HTML 테이블에 레코드 데이터 표시

7.6 "Read One Product"HTML 테이블 표시 및 페이지 제목 변경

7.7 출력


8.0 jQuery AJAX를 사용하여 데이터를 업데이트하는 방법? 

8.1 "udpate 제품"버튼 클릭 처리

8.2 제품 ID 받기

8.3 제품 정보 읽기

8.4 카테고리 목록 가져 오기

8.5 "제품 읽기"버튼 추가

8.6 "제품 업데이트"양식 작성

8.7 "제품 업데이트"양식 표시 및 페이지 제목 변경

8.8 "udpate 제품"양식 제출 처리

8.9 양식 데이터 가져 오기

8.10 서버로 양식 데이터 보내기

8.11 출력


9.0 jQuery AJAX를 사용하여 데이터를 삭제하는 방법? 

9.1 "제품 삭제"버튼 클릭 처리

9.2 제품 ID 얻기

9.3 "삭제 확인"대화 상자 표시

9.4 API를 사용하여 레코드 삭제

9.5 출력


10.0 jQuery AJAX를 사용하여 데이터를 검색하는 방법? 

10.1 index.html에 두 개의 JS 파일 포함

10.2 products.js 파일 생성

10.3 search-product.js 파일 생성

10.4 read-products.js 변경

10.5 출력


11.0 jQuery AJAX를 사용하여 데이터 페이지를 매기는 방법? 

11.1 JSON URL 변경

11.2 JSON URL을 사용하여 제품 표시

11.3 페이지 매김 HTML 추가

11.5 출력


17.0 다음은 무엇입니까?


1.0 개요 


AJAX 란 무엇입니까? "Asynchronous JavaScript and XML"을 의미합니다.


가장 간단한 방법으로 설명하겠습니다. AJAX를 사용하면 버튼을 클릭 할 때마다 전체 페이지가 다시 로드되는 것을 막습니다. 결과적으로 사용자 경험이 향상됩니다. 웹 앱이 더 빨라집니다.


Ajax는 기술이 아니라 기술 그룹입니다. 여기에는 HTML, CSS, JavaScript 및 PHP와 같은 서버 측 스크립팅이 포함될 수 있습니다.


여기서 진행하기 전에 먼저 이전 튜토리얼을 공부하는 것이 좋습니다. 하지만 이걸 가져갈 수 있다고 생각한다면 계속하세요.


이 튜토리얼은 데이터베이스 레코드 생성, 읽기, 업데이트 및 삭제에 중점을 둡니다. jQuery, JSON 및 PHP를 사용하여 수행합니다.


jQuery는 AJAX 부분에 도움이 될 것입니다. JSON 데이터는 PHP를 사용하여 빌드 된 REST API에 의해 처리됩니다.


2.0 프로그램 출력-PHP AJAX CRUD 튜토리얼 


다음은 스크립트 출력의 일부 스크린 샷입니다. 이미지를 클릭하면 더 큰 버전을 볼 수 있습니다. 왼쪽 및 오른쪽 화살표를 사용하여 스크린 샷을 탐색합니다.


2.1 LEVEL 1 소스 코드 출력 


2-read-records.jpg?fit=780%2C396&ssl=1 


3-create-record-1.jpg?fit=780%2C396&ssl=1 


4-read-one-record.jpg?fit=780%2C396&ssl=1 


5-update-record.jpg?fit=780%2C396&ssl=1 

6-delete-record.jpg?fit=780%2C396&ssl=1 


2.2 LEVEL 2 소스 코드 출력 


1-read-products.jpg?fit=780%2C396&ssl=1 


2-create-product-1.jpg?fit=780%2C396&ssl=1 



3-read-one-product-1.jpg?fit=780%2C396&ssl=1 

4-update-product-1.jpg?fit=780%2C396&ssl=1 


5-delete-product-1.jpg?fit=780%2C396&ssl=1 


2.3 LEVEL 3 소스 코드 출력 


2-products-tooltip.jpg?fit=730%2C372&ssl=1 


3-categories-inline-editing.jpg?fit=730%2C372&ssl=1 

4-categories-tooltip.jpg?fit=730%2C372&ssl=1 




1-products-inline-editing.jpg?fit=730%2C372&ssl=1 

LEVEL 2 및 3 소스 코드 출력은 더 많은 기능을 추가하고 사용자 정의 할 수 있음을 증명합니다. 아래 튜토리얼을 따라 배우면 더 쉽고 빠릅니다.


소스 코드를 다운로드하는 것도 큰 이점입니다. 지금은 LEVEL 1 소스 코드의 단계별 자습서를 진행하겠습니다. 즐겨!


3.0 REST API 설정 


이 튜토리얼에서는 PHP로 빌드 된 REST API를 사용합니다.


PHP가 아닌 AJAX로 코딩하는 방법을 배우는 데 집중하기를 바라기 때문에 REST API 소스 코드를 포함하지 않았습니다.


하지만 좋은 소식은 PHP로 간단한 REST API를 빌드 하는 방법에 대한 별도의 자습서를 만들었다는 것입니다. 단계별 PHP REST API 튜토리얼을 배우려면 여기를 클릭하십시오.


먼저 REST API 튜토리얼을 배우는 것이 좋습니다. 이 튜토리얼의 나머지 부분에서 해당 API를 사용할 것이기 때문입니다.


하지만 이 튜토리얼과 함께 작동하는 자체 REST API가 이미 있다면 괜찮습니다.


제 경우에는 REST API에 액세스 할 수 있는 한 가지 예가 있습니다. http : //localhost/api/product/read.php


이 링크는 데이터베이스의 제품 목록을 JSON 형식으로 표시합니다. 다음 스크린 샷과 같습니다.


read-records-json.jpg?resize=730%2C372&ssl=1 



위의 데이터는 AJAX 앱에서 사용됩니다. 제품 목록은 "Read One", "Update"및 "Delete"와 같은 버튼과 함께 Bootstrap 테이블에 표시됩니다. "JQuery AJAX를 사용하여 JSON 데이터를 읽는 방법"에서 확인할 수 있습니다. 이 튜토리얼의 섹션.


그건 그렇고, 브라우저에서 JSON 데이터를 읽을 수 있도록 JSONView라는 Chrome 확장 프로그램을 사용하고 있습니다.


4.0 기본 파일 및 폴더 


4.1 파일 구조 


이 LEVEL 1 소스 코드 튜토리얼의 끝에 다음 파일과 폴더가 있습니다.


├─ app/
├─── assets/
├────── css/
├───────── style.css
├────── js/
├───────── bootbox.min.js
├───────── jquery.js
├─── products/
├────── create-product.js
├────── delete-product.js
├────── read-one-product.js
├────── read-products.js
├────── update-product.js
├─── app.js
├─ index.html 


다음 섹션에서는 위의 파일과 폴더를 만들기 시작합니다.


4.2 index.html 파일 생성 


프로젝트의 기본 폴더에 index.html 파일을 만듭니다. 해당 파일을 열고 다음 코드를 입력하십시오.


<!DOCTYPE html>
<html lang="en">
<head>
 
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
 
    <title>Read Products</title>
 
    <!-- bootstrap CSS -->
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
 
    <!-- custom CSS -->
    <link href="app/assets/css/style.css" rel="stylesheet" />
 
</head>
<body>
 
<!-- our app will be injected here -->
<div id="app"></div>
 
<!-- jQuery library -->
<script src="app/assets/js/jquery.js"></script>
 
<!-- bootstrap JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
 
<!-- bootbox for confirm pop up -->
<script src="app/assets/js/bootbox.min.js"></script>
 
<!-- app js script -->
<script src="app/app.js"></script>
 
<!-- products scripts -->
<script src="app/products/read-products.js"></script>
<script src="app/products/create-product.js"></script>
<script src="app/products/read-one-product.js"></script>
<script src="app/products/update-product.js"></script>
<script src="app/products/delete-product.js"></script>
 
</body>
</html>


4.3 부트 스트랩 활성화 


위의 index.html 파일에서 볼 수 있듯이 CDN을 통해 부트 스트랩을 활성화했습니다.


다운로드를 통해 부트 스트랩을 활성화 해야 하는 경우에도 작동합니다.


4.4 사용자 지정 CSS 파일 만들기 


  1. "app"폴더를 만듭니다.
  2. "app"폴더를 열고 "assets"폴더를 만듭니다.
  3. "assets"폴더를 열고 "css"폴더를 만듭니다.
  4. "css"폴더를 열고 "style.css"파일을 만듭니다.

"style.css"파일은 사용자 정의 CSS 파일입니다. 추가 웹 페이지 스타일링을 위해 이 파일에 CSS를 넣을 수 있습니다. 우리의 경우 "style.css"파일 내에 다음 CSS 코드가 있습니다.


.m-r-10px{ margin-right:10px; }
.m-b-10px{ margin-bottom:10px; }
.m-b-15px{ margin-bottom:15px; }
.m-b-20px{ margin-bottom:20px; }
.w-5-pct{ width:5%; }
.w-10-pct{ width:10%; }
.w-15-pct{ width:15%; }
.w-20-pct{ width:20%; }
.w-25-pct{ width:25%; }
.w-30-pct{ width:30%; }
.w-35-pct{ width:35%; }
.w-40-pct{ width:40%; }
.w-45-pct{ width:45%; }
.w-50-pct{ width:50%; }
.w-55-pct{ width:55%; }
.w-60-pct{ width:60%; }
.w-65-pct{ width:65%; }
.w-70-pct{ width:70%; }
.w-75-pct{ width:75%; }
.w-80-pct{ width:80%; }
.w-85-pct{ width:85%; }
.w-90-pct{ width:90%; }
.w-95-pct{ width:95%; }
.w-100-pct{ width:100%; }
.display-none{ display:none; }
.padding-bottom-2em{ padding-bottom:2em; }
.width-30-pct{ width:30%; }
.width-40-pct{ width:40%; }
.overflow-hidden{ overflow:hidden; }
.margin-right-1em{ margin-right:1em; }
.right-margin{ margin:0 .5em 0 0; }
.margin-bottom-1em { margin-bottom:1em; }
.margin-zero{ margin:0; }
.text-align-center{ text-align:center; }


4.5 jQuery 및 Bootbox.js 라이브러리 다운로드 


  1. "app"폴더를 엽니다.
  2. "app"폴더 안의 "assets"폴더를 엽니다.
  3. "assets"폴더 안에 "js"폴더를 만듭니다.


"js"폴더에는 jQuery 및 Bootbox.js 라이브러리가 있습니다.


간단한 앱을 간단하게 만들려면 jQuery JavaScript 라이브러리가 필요합니다. 이 링크에서 jQuery를 다운로드하십시오.


"삭제"확인 대화 상자를 더 보기 좋게 만들려면 Bootbox.js 라이브러리가 필요합니다. 이 링크에서 Bootbox.js를 다운로드하십시오.


이러한 JavaScript 라이브러리에 대한 CDN도 있습니다. 원하는 경우 사용할 수 있지만 다운로드 한 버전을 선호합니다. 둘 다 작동합니다.


4.6 app.js 파일 생성 


"app.js"파일에는 앱의 다른 JS 파일에서 사용할 수 있는 몇 가지 기본 HTML 및 JavaScript 함수가 포함되어 있습니다.


  1. "app"폴더를 엽니다.
  2. 그 "app"폴더 안에 "app.js"파일을 만듭니다.
  3. "app.js"파일을 열고 다음 코드를 입력합니다.
$(document).ready(function(){
 
    // app html
    var app_html=`
        <div class='container'>
 
            <div class='page-header'>
                <h1 id='page-title'>Read Products</h1>
            </div>
 
            <!-- this is where the contents will be shown. -->
            <div id='page-content'></div>
 
        </div>`;
 
    // inject to 'app' in index.html
    $("#app").html(app_html);
 
});
 
// change page title
function changePageTitle(page_title){
 
    // change page title
    $('#page-title').text(page_title);
 
    // change title tag
    document.title=page_title;
}
 
// function to make form values to json format
$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};



4.7 "제품"스크립트 생성 


이제 몇 개의 JavaScript 파일을 만들 것입니다.


  1. "app"폴더를 엽니다.
  2. "app"폴더 안에 "products"폴더를 만듭니다.
  3. "products"폴더에 다음 파일을 만듭니다.
    read-products.js
    create-product.js
    read-one-product.js
    update-product.js
    delete-product.js

위의 JavaScript 파일 안에 있는 코드는 무엇입니까? 지금은 비워 두겠습니다. 그러나 우리는 이 튜토리얼의 다음 몇 섹션에서 그것들을 채울 것입니다.


4.8 출력 


지금까지의 코드는 거의 빈 출력을 가질 것입니다. 다음과 같이 보일 것입니다.


1-output-ajax-crud-tutorial.jpg?resize=780%2C396&ssl=1 

5.0 JQUERY AJAX를 사용하여 JSON 데이터를 읽는 방법? 


5.1 첫 페이지로드시 제품 표시 


  1. "app"폴더를 엽니다.
  2. "app"폴더 안에 있는 "products"폴더를 엽니다.
  3. "products"폴더에있는 read-products.js 파일을 엽니다.

다음 코드는 웹 페이지를 처음 로드 할 때 showProducts() 메서드를 호출합니다.


showProducts()는 HTML 테이블에 제품 목록을 표시합니다. read-products.js 파일에 다음 코드를 넣으십시오.


$(document).ready(function(){
 
    // show list of product on first load
    showProducts();
 
});
 
// showProducts() method will be here



5.2 버튼 클릭시 제품 표시 


다음 코드는 read-products-button 클래스가 있는 버튼을 클릭하면 showProducts() 메서드를 호출합니다.


이 버튼은 "제품 생성"및 "제품 업데이트"HTML 템플릿에서 찾을 수 있습니다. 다음 섹션에서 살펴 보겠습니다.


다음 코드를  이전 섹션의 showProducts(); 아래에 넣으십시오.


// when a 'read products' button was clicked
$(document).on('click', '.read-products-button', function(){
    showProducts();
});


5.3 showProducts() 함수 생성 


이제 showProducts() 메서드를 만듭니다. // showProducts() 메서드는 read-products.js 파일의 주석이 다음 코드로 대체됩니다.


// function to show list of products
function showProducts(){
 
}


5.4 제품 목록 가져 오기 


다음 코드는 API에 연결하여 JSON 형식의 제품 목록을 가져옵니다. 이전 섹션의 여는 중괄호 뒤에 다음 코드를 추가합니다.


// get list of products from the API
$.getJSON("http://localhost/api/product/read.php", function(data){
 
});


5.5 "제품 생성"버튼 추가 


"제품 목록"보기에 "제품 생성"버튼을 추가해야 합니다. 이 튜토리얼의 뒷부분에서 이 버튼이 작동하도록 할 것입니다.


이전 섹션의 여는 중괄호 뒤에 다음 코드를 추가합니다.


// html for listing products
var read_products_html=`
    <!-- when clicked, it will load the create product form -->
    <div id='create-product' class='btn btn-primary pull-right m-b-15px create-product-button'>
        <span class='glyphicon glyphicon-plus'></span> Create Product
    </div>


5.6 HTML 테이블 작성 


제품 목록이 표시 될 HTML 테이블을 작성해야 합니다.


다음 코드는 제목이 있는 HTML 테이블을 작성합니다. 이전 섹션의 코드 뒤에 배치하십시오.


<!-- start table -->
<table class='table table-bordered table-hover'>
 
    <!-- creating our table heading -->
    <tr>
        <th class='w-25-pct'>Name</th>
        <th class='w-10-pct'>Price</th>
        <th class='w-15-pct'>Category</th>
        <th class='w-25-pct text-align-center'>Action</th>
    </tr>`;
     
    // rows will be here
 
// end table
read_products_html+=`</table>`;


5.7 레코드 당 테이블 행 작성 


API에서 반환 한 각 레코드를 반복합니다. 각 레코드에서 테이블 행을 생성합니다.


제품 데이터 외에 표 행에는 '작업'버튼도 있습니다. 여기에는 "Read One", "Edit"및 "Delete"버튼이 포함됩니다.


이전 섹션의 "// rows will be here"주석을 다음 코드로 바꿉니다.


// loop through returned list of data
$.each(data.records, function(key, val) {
 
    // creating new table row per record
    read_products_html+=`
        <tr>
 
            <td>` + val.name + `</td>
            <td>$` + val.price + `</td>
            <td>` + val.category_name + `</td>
 
            <!-- 'action' buttons -->
            <td>
                <!-- read product button -->
                <button class='btn btn-primary m-r-10px read-one-product-button' data-id='` + val.id + `'>
                    <span class='glyphicon glyphicon-eye-open'></span> Read
                </button>
 
                <!-- edit button -->
                <button class='btn btn-info m-r-10px update-product-button' data-id='` + val.id + `'>
                    <span class='glyphicon glyphicon-edit'></span> Edit
                </button>
 
                <!-- delete button -->
                <button class='btn btn-danger delete-product-button' data-id='` + val.id + `'>
                    <span class='glyphicon glyphicon-remove'></span> Delete
                </button>
            </td>
 
        </tr>`;
});



5.8 페이지 콘텐츠에 삽입 


웹 페이지에 HTML 테이블이 나타나도록해야합니다. "page-content"div에 테이블을 삽입하여 이를 수행합니다.


닫는 "table"태그 뒤에 다음 코드를 추가합니다.


// inject to 'page-content' of our app
$("#page-content").html(read_products_html);


5.9 페이지 제목 변경 


다음 코드는 웹 페이지에 표시되는 "제목"과 브라우저 탭에 표시되는 "제목"을 변경합니다.


이전 섹션의 코드 뒤에 다음 코드를 추가합니다.


// chage page title
changePageTitle("Read Products");


5.10 출력 


위의 모든 단계를 수행 한 후 출력은 다음과 같아야 합니다.


2-read-records.jpg?resize=780%2C396&ssl=1 


6.0 JQUERY AJAX를 사용하여 데이터를 생성하거나 삽입하는 방법은 무엇입니까? 


6.1 "제품 생성"버튼 클릭 처리 


  1. "app"폴더를 엽니다.
  2. "app"폴더 안에 있는 "products"폴더를 엽니다.
  3. "products"폴더에서 create-product.js 파일을 엽니다.

다음 코드는 버튼 클릭을 처리합니다. 이 버튼에는 "제품 생성 버튼"클래스가 있어야 합니다.


create-product.js 파일에 다음 코드를 넣습니다.


$(document).ready(function(){
 
    // show html form when 'create product' button was clicked
    $(document).on('click', '.create-product-button', function(){
        // categories api call will be here
    });
 
    // 'create product form' handle will be here
});


6.2 API에서 카테고리 목록 가져 오기 


"categories"선택 필드를 만들 것이므로 API에서 범주 목록을 가져와야 합니다. 사용자가 제품의 카테고리를 선택할 수 있는 곳입니다.


이전 섹션의 "// categories api call will be here"를 다음 코드로 바꿉니다.


// load list of categories
$.getJSON("http://localhost/api/category/read.php", function(data){
 
});


6.3 "카테고리 옵션"선택 필드 작성 


여기에서 "categories"옵션을 사용하여 HTML "select"필드를 작성합니다.


이전 섹션의 여는 중괄호 뒤에 다음 코드를 추가합니다.


// build categories option html
// loop through returned list of data
var categories_options_html=`<select name='category_id' class='form-control'>`;
$.each(data.records, function(key, val){
    categories_options_html+=`<option value='` + val.id + `'>` + val.name + `</option>`;
});
categories_options_html+=`</select>`;


6.4 "제품 읽기"버튼 추가 


제품 목록으로 돌아가려면 "제품 읽기"버튼이 필요합니다.


이전 섹션의 코드 뒤에 다음 코드를 추가합니다.


// we have our html form here where product information will be entered
// we used the 'required' html5 property to prevent empty fields
var create_product_html=`
 
    <!-- 'read products' button to show list of products -->
    <div id='read-products' class='btn btn-primary pull-right m-b-15px read-products-button'>
        <span class='glyphicon glyphicon-list'></span> Read Products
    </div>


6.5 "제품 생성"HTML 양식 작성 


이제 실제 "제품 생성"HTML 양식을 작성합니다. 여기에서 사용자는 서버로 보낼 신제품 정보를 입력 할 수 있습니다.


이전 섹션의 코드 뒤에 다음 코드를 추가합니다.


<!-- 'create product' html form -->
<form id='create-product-form' action='#' method='post' border='0'>
    <table class='table table-hover table-responsive table-bordered'>
 
        <!-- name field -->
        <tr>
            <td>Name</td>
            <td><input type='text' name='name' class='form-control' required /></td>
        </tr>
 
        <!-- price field -->
        <tr>
            <td>Price</td>
            <td><input type='number' min='1' name='price' class='form-control' required /></td>
        </tr>
 
        <!-- description field -->
        <tr>
            <td>Description</td>
            <td><textarea name='description' class='form-control' required></textarea></td>
        </tr>
 
        <!-- categories 'select' field -->
        <tr>
            <td>Category</td>
            <td>` + categories_options_html + `</td>
        </tr>
 
        <!-- button to submit form -->
        <tr>
            <td></td>
            <td>
                <button type='submit' class='btn btn-primary'>
                    <span class='glyphicon glyphicon-plus'></span> Create Product
                </button>
            </td>
        </tr>
 
    </table>
</form>`;


6.6 "제품 생성"양식 표시 및 페이지 제목 변경 


웹 페이지에 HTML 버튼과 양식을 표시해야 합니다. 페이지 제목도 변경합니다.


이전 섹션의 코드 뒤에 다음 코드를 추가합니다.


// inject html to 'page-content' of our app
$("#page-content").html(create_product_html);
 
// chage page title
changePageTitle("Create Product");


6.7 "제품 생성"양식 제출 처리 


"제품 생성"양식이 제출되면 이를 처리 할 스크립트가 필요합니다.


"// 'Create product form'handle will be here"를 찾아 다음 코드로 바꿉니다.


// will run if create product form was submitted
$(document).on('submit', '#create-product-form', function(){
    // form data will be here
});


6.8 양식 데이터 가져 오기 


이것이 "제품 생성"HTML 양식에 입력 된 데이터를 얻는 방법입니다.


이전 섹션의 "// form data will be here"를 다음 코드로 바꿉니다.


// get form data
var form_data=JSON.stringify($(this).serializeObject());


6.9 서버로 데이터 보내기 


이제 데이터를 서버로 보냅니다.


이전 섹션의 코드 뒤에 다음 코드를 추가합니다.


// submit form data to api
$.ajax({
    type : "POST",
    contentType : 'application/json',
    data : form_data,
    success : function(result) {
        // product was created, go back to products list
        showProducts();
    },
    error: function(xhr, resp, text) {
        // show error to console
        console.log(xhr, resp, text);
    }
});
 
return false;


6.10 출력 


출력은 다음과 같아야 합니다.


3-create-record-1.jpg?resize=780%2C396&ssl=1 

7.0 JQUERY AJAX를 사용하여 하나의 데이터를 읽는 방법은 무엇입니까? 


7.1 "읽기"버튼 클릭 처리 


"read one"버튼은 "제품 목록"보기에 표시됩니다. 클릭하면 전체 제품 세부 정보가 표시됩니다.


  1. "app"폴더를 엽니다.
  2. "app"폴더 내에서 "products"폴더를 엽니다.
  3. "products"폴더 내에서 "read-one-product.js"파일을 엽니다.

"read-one-product.js"파일에 다음 코드를 넣으십시오.


$(document).ready(function(){
 
    // handle 'read one' button click
    $(document).on('click', '.read-one-product-button', function(){
        // product ID will be here
    });
 
});


7.2 제품 ID 얻기 


스크립트는 읽을 레코드를 식별해야 합니다. 제품 ID를 가져 와서 수행합니다.


이전 섹션의 "// product ID will be here"를 다음 코드로 바꿉니다.


// get product id
var id = $(this).attr('data-id');


7.3 API에서 하나의 레코드 읽기 


제품 ID를 API로 보냅니다. 주어진 ID를 기반으로 데이터를 반환합니다.


이전 섹션의 코드 뒤에 다음 코드를 추가합니다.


// read product record based on given ID
$.getJSON("http://localhost/api/product/read_one.php?id=" + id, function(data){
    // read products button will be here
});


7.4 "제품 읽기"버튼 추가 


제품 목록으로 돌아가려면 "제품 읽기"버튼이 필요합니다.


이전 섹션의 "// read products button will be here"를 다음 코드로 바꿉니다.


// start html
var read_one_product_html=`
 
    <!-- when clicked, it will show the product's list -->
    <div id='read-products' class='btn btn-primary pull-right m-b-15px read-products-button'>
        <span class='glyphicon glyphicon-list'></span> Read Products
    </div>


7.5 HTML 테이블에 레코드 데이터 표시 


API에서 반환 한 제품 정보를 HTML 테이블에 배치합니다.


이전 섹션의 코드 뒤에 다음 코드를 추가합니다.


<!-- product data will be shown in this table -->
<table class='table table-bordered table-hover'>
 
    <!-- product name -->
    <tr>
        <td class='w-30-pct'>Name</td>
        <td class='w-70-pct'>` + data.name + `</td>
    </tr>
 
    <!-- product price -->
    <tr>
        <td>Price</td>
        <td>` + data.price + `</td>
    </tr>
 
    <!-- product description -->
    <tr>
        <td>Description</td>
        <td>` + data.description + `</td>
    </tr>
 
    <!-- product category name -->
    <tr>
        <td>Category</td>
        <td>` + data.category_name + `</td>
    </tr>
 
</table>`;


7.6 "Read One Product"HTML 테이블 표시 및 페이지 제목 변경 


웹 페이지에 HTML 버튼과 테이블을 표시해야 합니다. 페이지 제목도 변경합니다.


이전 섹션의 코드 뒤에 다음 코드를 추가합니다.


// inject html to 'page-content' of our app
$("#page-content").html(read_one_product_html);
 
// chage page title
changePageTitle("Create Product");


7.7 출력 


출력은 다음과 같아야 합니다.

4-read-one-record.jpg?resize=780%2C396&ssl=1 


8.0 JQUERY AJAX를 사용하여 데이터를 업데이트하는 방법은 무엇입니까? 


8.1 "udpate 제품"버튼 클릭 처리 


"제품 목록"보기에 "수정"버튼이 표시됩니다. 클릭하면 제품 정보가 입력 된 "제품 업데이트"양식이 표시됩니다.


  1. "app"폴더를 엽니다.
  2. "app"폴더 내에서 "products"폴더를 엽니다.
  3. "products"폴더 내에서 "update-product.js"파일을 엽니다.

"update-product.js"파일에 다음 코드를 넣습니다.


$(document).ready(function(){
 
    // show html form when 'update product' button was clicked
    $(document).on('click', '.update-product-button', function(){
        // product ID will be here
    });
     
    // 'update product form' submit handle will be here
});


8.2 제품 ID 받기 


스크립트는 읽을 레코드를 식별해야 합니다. 제품 ID를 가져 와서 수행합니다.


이전 섹션의 "// product ID will be here"를 다음 코드로 바꿉니다.


// get product id
var id = $(this).attr('data-id');


8.3 제품 정보 읽기 


"제품 업데이트"HTML 양식을 작성하려면 API에서 제품 정보를 가져와야 합니다.


이전 섹션의 코드 뒤에 다음 코드를 추가합니다.


// read one record based on given product id
$.getJSON("http://localhost/api/product/read_one.php?id=" + id, function(data){
 
    // values will be used to fill out our form
    var name = data.name;
    var price = data.price;
    var description = data.description;
    var category_id = data.category_id;
    var category_name = data.category_name;
     
    // load list of categories will be here
});


8.4 카테고리 목록 가져 오기 


카테고리 목록은 제품의 카테고리 옵션에 필요합니다. 카테고리 레코드는 "선택"HTML 입력 필드의 옵션으로 렌더링 됩니다.


이전 섹션의 "// load list of categories will be here"를 다음 코드로 바꿉니다.


// load list of categories
$.getJSON("http://localhost/api/category/read.php", function(data){
 
    // build 'categories option' html
    // loop through returned list of data
        var categories_options_html=`<select name='category_id' class='form-control'>`;
 
        $.each(data.records, function(key, val){
            // pre-select option is category id is the same
            if(val.id==category_id){ categories_options_html+=`<option value='` + val.id + `' selected>` + val.name + `</option>`; }
 
            else{ categories_options_html+=`<option value='` + val.id + `'>` + val.name + `</option>`; }
        });
        categories_options_html+=`</select>`;
     
    // update product html will be here
});



8.5 "제품 읽기"버튼 추가 


제품 목록으로 돌아가려면 "제품 읽기"버튼이 필요합니다.


이전 섹션의 "// update product html will be here"를 다음 코드로 바꿉니다.


// store 'update product' html to this variable
var update_product_html=`
    <div id='read-products' class='btn btn-primary pull-right m-b-15px read-products-button'>
        <span class='glyphicon glyphicon-list'></span> Read Products
    </div>


8.6 "제품 업데이트"양식 작성 


이제 "udpate 제품"HTML 양식을 작성합니다. 이 양식은 HTML 테이블로 작성되며 입력 필드는 제품 정보로 채워집니다.


이전 섹션의 코드 뒤에 다음 코드를 추가합니다.


<!-- build 'update product' html form -->
<!-- we used the 'required' html5 property to prevent empty fields -->
<form id='update-product-form' action='#' method='post' border='0'>
    <table class='table table-hover table-responsive table-bordered'>
 
        <!-- name field -->
        <tr>
            <td>Name</td>
            <td><input value=\"` + name + `\" type='text' name='name' class='form-control' required /></td>
        </tr>
 
        <!-- price field -->
        <tr>
            <td>Price</td>
            <td><input value=\"` + price + `\" type='number' min='1' name='price' class='form-control' required /></td>
        </tr>
 
        <!-- description field -->
        <tr>
            <td>Description</td>
            <td><textarea name='description' class='form-control' required>` + description + `</textarea></td>
        </tr>
 
        <!-- categories 'select' field -->
        <tr>
            <td>Category</td>
            <td>` + categories_options_html + `</td>
        </tr>
 
        <tr>
 
            <!-- hidden 'product id' to identify which record to delete -->
            <td><input value=\"` + id + `\" name='id' type='hidden' /></td>
 
            <!-- button to submit form -->
            <td>
                <button type='submit' class='btn btn-info'>
                    <span class='glyphicon glyphicon-edit'></span> Update Product
                </button>
            </td>
 
        </tr>
 
    </table>
</form>`;


8.7 "제품 업데이트"양식 표시 및 페이지 제목 변경 


웹 페이지에 "제품 업데이트"HTML을 표시해야 합니다. 페이지 제목도 변경합니다.


이전 섹션의 코드 뒤에 다음 코드를 넣으십시오.


// inject to 'page-content' of our app
$("#page-content").html(update_product_html);
 
// chage page title
changePageTitle("Update Product");


8.8 "udpate 제품"양식 제출 처리 


"제품 업데이트"양식이 제출되면 이를 처리 할 스크립트가 필요합니다.


"// '업데이트 제품 양식'제출 핸들이 여기에 있습니다"를 찾아 다음 코드로 바꿉니다.


// will run if 'create product' form was submitted
$(document).on('submit', '#update-product-form', function(){
     
    // get form data will be here
     
    return false;
});


8.9 양식 데이터 가져 오기 


"제품 업데이트"HTML 양식에서 제품 정보를 가져옵니다.


이전 섹션의 "// get form data will be here"를 다음 코드로 바꿉니다.


// get form data
var form_data=JSON.stringify($(this).serializeObject());


8.10 서버로 양식 데이터 보내기 


양식 데이터를 가져온 후 데이터를 API로 보냅니다.


이전 섹션의 코드 뒤에 다음 코드를 추가합니다.


// submit form data to api
$.ajax({
    type : "POST",
    contentType : 'application/json',
    data : form_data,
    success : function(result) {
        // product was created, go back to products list
        showProducts();
    },
    error: function(xhr, resp, text) {
        // show error to console
        console.log(xhr, resp, text);
    }
});


8.11 출력 


출력은 다음과 같아야 합니다.

5-update-record.jpg?resize=780%2C396&ssl=1 



9.0 JQUERY AJAX를 사용하여 데이터를 삭제하는 방법은 무엇입니까? 


9.1 "제품 삭제"버튼 클릭 처리 


"제품 삭제"버튼은 "제품 읽기"보기에 표시됩니다. 클릭했을 때 처리해야 합니다.


  1. "app"폴더를 엽니다.
  2. "app"폴더 내에서 "products"폴더를 엽니다.
  3. "products"폴더에서 "delete-product.js"파일을 엽니다.

"delete-product.js"파일에 다음 코드를 넣습니다.


$(document).ready(function(){
 
    // will run if the delete button was clicked
    $(document).on('click', '.delete-product-button', function(){
        // product id will be here
    });
});


9.2 제품 ID 얻기 


API를 사용하여 삭제할 레코드를 식별하려면 제품 ID가 필요합니다.


이전 섹션의 "// product id will be here"를 다음 코드로 바꿉니다.


// get the product id
var product_id = $(this).attr('data-id');


9.3 "삭제 확인"대화 상자 표시 


여기서 Bootbox.js 라이브러리를 사용할 것입니다. "계속 하시겠습니까?"라는 대화 상자가 표시됩니다. "예"및 "아니오"버튼이 있는 메시지.


이전 섹션의 코드 뒤에 다음 코드를 추가합니다.


// bootbox for good looking 'confirm pop up'
bootbox.confirm({
 
    message: "<h4>Are you sure?</h4>",
    buttons: {
        confirm: {
            label: '<span class="glyphicon glyphicon-ok"></span> Yes',
            className: 'btn-danger'
        },
        cancel: {
            label: '<span class="glyphicon glyphicon-remove"></span> No',
            className: 'btn-primary'
        }
    },
    callback: function (result) {
        // delete request will be here
    }
});


9.4 API를 사용하여 레코드 삭제 


사용자가 대화 상자에서 "예"를 클릭하면 "삭제"요청이 API로 전송됩니다.


이전 섹션의 "// delete request will be here"를 다음 코드로 바꿉니다.


if(result==true){
 
    // send delete request to api / remote server
    $.ajax({
        type : "POST",
        dataType : 'json',
        data : JSON.stringify({ id: product_id }),
        success : function(result) {
 
            // re-load list of products
            showProducts();
        },
        error: function(xhr, resp, text) {
            console.log(xhr, resp, text);
        }
    });
 
}


9.5 출력 


6-delete-record.jpg?resize=780%2C396&ssl=1 


10.0 JQUERY AJAX를 사용하여 데이터를 검색하는 방법은 무엇입니까? 


이 기능은 LEVEL 2 소스 코드의 일부입니다.


10.1 index.html에 두 개의 JS 파일 포함 


<!-- products scripts -->
<script src="app/products/products.js"></script>
<script src="app/products/search-product.js"></script>


10.2 products.js 파일 생성 


"products.js"파일에는 "read-products.js"또는 "search-products.js"파일과 같은 다른 제품 구성 요소에서 사용할 수 있는 모든 함수가 포함됩니다.


"app"폴더를 엽니다. "products"폴더를 엽니다. "products.js"파일을 만듭니다.


"products.js"파일을 열고 다음 코드를 입력하십시오.


// product list html
function readProductsTemplate(data, keywords){
 
    var read_products_html=`
        <!-- search products form -->
        <form id='search-product-form' action='#' method='post'>
        <div class='input-group pull-left w-30-pct'>
 
            <input type='text' value='` + keywords + `' name='keywords' class='form-control product-search-keywords' placeholder='Search products...' />
 
            <span class='input-group-btn'>
                <button type='submit' class='btn btn-default' type='button'>
                    <span class='glyphicon glyphicon-search'></span>
                </button>
            </span>
 
        </div>
        </form>
 
        <!-- when clicked, it will load the create product form -->
        <div id='create-product' class='btn btn-primary pull-right m-b-15px create-product-button'>
            <span class='glyphicon glyphicon-plus'></span> Create Product
        </div>
 
        <!-- start table -->
        <table class='table table-bordered table-hover'>
 
            <!-- creating our table heading -->
            <tr>
                <th class='w-25-pct'>Name</th>
                <th class='w-10-pct'>Price</th>
                <th class='w-15-pct'>Category</th>
                <th class='w-25-pct text-align-center'>Action</th>
            </tr>`;
 
 
    // loop through returned list of data
    $.each(data.records, function(key, val) {
 
        // creating new table row per record
        read_products_html+=`<tr>
 
            <td>` + val.name + `</td>
            <td>$` + val.price + `</td>
            <td>` + val.category_name + `</td>
 
            <!-- 'action' buttons -->
            <td>
                <!-- read product button -->
                <button class='btn btn-primary m-r-10px read-one-product-button' data-id='` + val.id + `'>
                    <span class='glyphicon glyphicon-eye-open'></span> Read
                </button>
 
                <!-- edit button -->
                <button class='btn btn-info m-r-10px update-product-button' data-id='` + val.id + `'>
                    <span class='glyphicon glyphicon-edit'></span> Edit
                </button>
 
                <!-- delete button -->
                <button class='btn btn-danger delete-product-button' data-id='` + val.id + `'>
                    <span class='glyphicon glyphicon-remove'></span> Delete
                </button>
            </td>
        </tr>`;
    });
 
    // end table
    read_products_html+=`</table>`;
 
    // inject to 'page-content' of our app
    $("#page-content").html(read_products_html);
}


10.3 search-product.js 파일 생성 


"search-product.js"파일에는 "검색 제품"양식의 제출을 ​​포착하는 코드가 포함됩니다.


"app"폴더를 엽니다. "products"폴더를 엽니다. "search-products.js"파일을 만듭니다.


"search-products.js"파일을 열고 다음 코드를 입력하십시오.


$(document).ready(function(){
 
    // when a 'search products' button was clicked
    $(document).on('submit', '#search-product-form', function(){
 
        // get search keywords
        var keywords = $(this).find(":input[name='keywords']").val();
 
        // get data from the api based on search keywords
        $.getJSON("http://localhost/api/product/search.php?s=" + keywords, function(data){
 
            // template in products.js
            readProductsTemplate(data, keywords);
 
            // chage page title
            changePageTitle("Search products: " + keywords);
 
        });
 
        // prevent whole page reload
        return false;
    });
 
});


10.4 read-products.js 변경 


"제품 목록"과 "제품 검색"에 동일한 HTML 테이블 템플릿이 있어야 합니다. 이를 위해 products.js 파일의 readProductsTemplate() 함수를 사용합니다.


"app"폴더를 엽니다. "products"폴더를 엽니다. "read-products.js '파일을 열고 showProducts() 함수를 다음 코드로 변경합니다.


// function to show list of products
function showProducts(){
 
    // get list of products from the API
    $.getJSON("http://localhost/api/product/read.php", function(data){
 
        // html for listing products
        readProductsTemplate(data, "");
 
        // chage page title
        changePageTitle("Read Products");
 
    });
}


10.5 출력 


output-search-product.jpg?resize=780%2C396&ssl=1 

11.0 JQUERY AJAX를 사용하여 데이터를 페이지화하는 방법은 무엇입니까? 


이 기능은 LEVEL 2 및 LEVEL 3 소스 코드의 일부입니다.


11.1 JSON URL 변경 


페이지 매김이 작동하도록 하려면 JSON URL을 변경해야 합니다. 이 새 JSON 데이터의 내용에는 "페이징"노드가 포함됩니다. 다음과 같이 보입니다.


json-api-paging-node.jpg?resize=619%2C684&ssl=1 


따라서 JSON URL을 다음과 같이 변경합니다.






그것은 우리가 코드에서 무언가를 변경해야 한다는 것을 의미합니다. 다음 섹션의 변경 사항을 참조하십시오.


11.2 JSON URL을 사용하여 제품 표시 


/app/products/read-products.js 파일을 엽니다. 코드를 다음으로 바꿉니다.


$(document).ready(function(){
 
    // show list of product on first load
    showProductsFirstPage();
 
    // when a 'read products' button was clicked
    $(document).on('click', '.read-products-button', function(){
        showProductsFirstPage();
    });
 
    // when a 'page' button was clicked
    $(document).on('click', '.pagination li', function(){
        // get json url
        var json_url=$(this).find('a').attr('data-page');
 
        // show list of products
        showProducts(json_url);
    });
 
 
});
 
function showProductsFirstPage(){
    showProducts(json_url);
}
 
// function to show list of products
function showProducts(json_url){
 
    // get list of products from the API
    $.getJSON(json_url, function(data){
 
        // html for listing products
        readProductsTemplate(data, "");
 
        // chage page title
        changePageTitle("Read Products");
 
    });
}


11.3 페이지 매김 HTML 추가 


/app/products/products.js 파일을 엽니다. 끝 "table"태그를 찾아 그 아래에 다음 코드를 넣습니다.


// pagination
if(data.paging){
    read_products_html+="<ul class='pagination pull-left margin-zero padding-bottom-2em'>";
 
        // first page
        if(data.paging.first!=""){
            read_products_html+="<li><a data-page='" + data.paging.first + "'>First Page</a></li>";
        }
 
        // loop through pages
        $.each(data.paging.pages, function(key, val){
            var active_page=val.current_page=="yes" ? "class='active'" : "";
            read_products_html+="<li " + active_page + "><a data-page='" + val.url + "'>" + val.page + "</a></li>";
        });
 
        // last page
        if(data.paging.last!=""){
            read_products_html+="<li><a data-page='" + data.paging.last + "'>Last Page</a></li>";
        }
    read_products_html+="</ul>";
}


11.5 출력 


위에서 변경 한 후 index.html을 다시 실행하십시오. 하드 새로 고침을 수행하십시오. 아래와 같은 페이징 버튼이 보일 것입니다.

ajax-crud-tutorial-pagination.jpg?resize=730%2C372&ssl=1 


12.0 소스 코드를 실행하는 방법? 


먼저 위의 잘 설명 된 단계별 자습서를 따르고 공부하는 것이 좋습니다. 학습에 있어 경험을 능가하는 것은 없습니다.


하지만 최종 소스 코드도 볼 수 있다면 더 빨리 배울 수 있을 것입니다. 추가 가이드로 간주합니다.


그것이 당신에게 가져올 가치 또는 기술 업그레이드를 상상해보십시오. 직장, 프로젝트 또는 사업에서 얻을 수 있는 추가 수입. 당신이 절약하는 소중한 시간. 그것이 당신이 원하는 것이 아닙니까?


지금까지 소스 코드를 다운로드 해야 합니다. 이를 수행하려면 다음 몇 섹션에서 다운로드 버튼을 사용하십시오.


소스 코드를 다운로드 한 후 실행하는 방법은 다음과 같습니다.


  1. 서버 디렉토리에 파일을 추출하십시오.
  2. "api"폴더 내의 README.txt를 따라 "api"를 설정하십시오.
  3. 브라우저를 열고 index.html을 실행하십시오.
  4. "제품"레코드 목록이 표시되면 설정이 올바른 것입니다.


댓글목록 0

등록된 댓글이 없습니다.

웹학교 로고

온라인 코딩학교

코리아뉴스 2001 - , All right reserved.