HTML 형식으로 배열을 게시하고 PHP에서 데이터를 처리하는 방법에 대한 자습서에 오신 것을 환영합니다.
HTML 형식으로 데이터를 처리하는 것은 쉽습니다. 입력 필드 나 텍스트 상자에 이름 속성을 추가하기 만하면 됩니다.
그러나 대신 배열을 게시하려면 어떻게 해야 합니까? 간단히 말해서 – HTML 양식에서 배열을 게시하려면 입력 필드의 이름 속성 끝에 대괄호 쌍을 추가하기 만하면 됩니다.
예를 들면 <input name =”favorites []”type =”text”>입니다.
그러나 Javascript 에서 이 작업을 수행하는 것은 어떻습니까? 다차원 배열은 어떻습니까?
PHP에서 포스트 데이터를 어떻게 처리합니까? 이것이 본 안내서에서 예를 통해 살펴볼 것입니다. 알아 보려면 계속 읽으십시오!
ⓘ이 튜토리얼을 시작할 때 모든 예제 소스 코드가 포함 된 zip 파일을 포함 시켰으므로 모든 내용을 복사하여 붙여 넣을 필요가 없습니다.
다운로드
먼저 약속 된 예제 소스 코드에 대한 다운로드 링크가 있습니다.
소스 코드 다운로드
소스 코드를 다운로드하려면 여기를 클릭하십시오. MIT 라이센스에 따라 릴리스되었으므로 그 위에 빌드하거나 자신의 프로젝트에서 자유롭게 사용하십시오.
빠른 시작
기본
소화하기 쉬운 것으로 시작합시다 – 초보자를 위한 HTML 양식을 간단히 살펴보면, 이미 코드 닌자라면 이 섹션을 건너 뛰어도 됩니다.
HTML
<html> <head> <title> Basic HTML Form </title> <style> /* [DOES NOT MATTER, JUST COSMETICS] */ form { font-family: arial, sans-serif; max-width: 300px; } label, input { display: block; width: 100%; margin: 5px 0; padding: 5px; box-sizing: border-box; } input[type=submit] { background: #305ba0; color: #fff; border: 0; margin-top: 10px; } </style> </head> <body> <form method="post" action="1b-server.php"> <label>Name</label> <input type="text" name="user-name" required value="John Doe"/> <label>Email</label> <input type="email" name="user-email" required value="john@doe.com"/> <input type="submit" value="Submit"/> </form> </body> </html>
서버 측 PHP
// The $_POST superglobal variable will contain all the form data // Just dump it if you need to debug and see what is being submitted print_r($_POST); echo "<br><br>"; // $_POST is an array. // We can easily retrieve the submitted form data with: // $_POST['user-name'] contains the name echo "USER NAME: " . $_POST['user-name'] . "<br>"; // $_POST['user-email'] contains the email echo "USER EMAIL: " . $_POST['user-email'] . "<br>";
형태의 배열
이제 HTML 양식 기본 사항을 다뤘으므로 백만 달러짜리 질문 – HTML 양식으로 배열을 보내는 방법으로 넘어가겠습니다.
HTML
<html> <head> <title> HTML array in Form Demo </title> <style> /* [DOES NOT MATTER, JUST COSMETICS] */ form { font-family: arial, sans-serif; max-width: 300px; } label, input { display: block; width: 100%; margin: 5px 0; padding: 5px; box-sizing: border-box; } input[type=submit] { background: #305ba0; color: #fff; border: 0; margin-top: 10px; } </style> </head> <body> <form method="post" action="2b-server.php"> <label>Name</label> <input type="text" name="user-name" required value="John Doe"/> <label>Email</label> <input type="email" name="user-email" required value="john@doe.com"/> <!-- To send as an array, use square brackets in the name --> <label>Favorite Colors</label> <input type="text" name="user-color[]" required value="red"/> <input type="text" name="user-color[]" required value="green"/> <input type="text" name="user-color[]"/> <input type="submit" value="Submit"/> </form> </body> </html>
네, 그렇게 어렵지는 않습니다.
SERVER-SIDE PHP
// For debugging - Dump if you want to see what is being submitted print_r($_POST); echo "<br><br>"; // You know this part... echo "USER NAME: " . $_POST['user-name'] . "<br>"; echo "USER EMAIL: " . $_POST['user-email'] . "<br>"; // This can be a little confusing for beginners. // $_POST is an array. $_POST['user-color'] is now an array within $_POST. echo "FAV COLORS: <br>"; foreach ($_POST['user-color'] as $color) { echo $color . "<br>"; }
다차원 배열
다차원 배열을 원한다면 어떻게 해야 할까요? 배열 내에 배열을 게시하려면? 다음 단계로 넘어 갑시다.
HTML
<html> <head> <title> HTML array in Form Demo </title> <style> /* [DOES NOT MATTER, JUST COSMETICS] */ form { font-family: arial, sans-serif; max-width: 300px; } label, input { display: block; width: 100%; margin: 5px 0; padding: 5px; box-sizing: border-box; } input[type=submit] { background: #305ba0; color: #fff; border: 0; margin-top: 10px; } </style> </head> <body> <form method="post" action="3b-server.php"> <label>Name</label> <input type="text" name="user-name" required value="John Doe"/> <label>Email</label> <input type="email" name="user-email" required value="john@doe.com"/> <!-- We can define multi-dimensional form fields similar to arrays in PHP --> <!-- Use 2 square brackets, give the first one a key for better organization --> <label>Favorite Colors</label> <input type="text" name="user-fav[color][]" required value="red"/> <input type="text" name="user-fav[color][]" required value="green"/> <input type="text" name="user-fav[color][]"/> <label>Favorite Food</label> <input type="text" name="user-fav[food][]" required value="bacon"/> <input type="text" name="user-fav[food][]" required value="eggs"/> <input type="text" name="user-fav[food][]" value=""/> <input type="submit" value="Submit"/> </form> </body> </html>
다차원 양식 필드도 그렇게 어렵지 않습니다. – 대괄호 2 개만 사용하고 첫 번째 키는 키를 제공하십시오. 그게 다야.
SERVER-SIDE PHP
// For debugging - Dump if you want to see what is being submitted print_r($_POST); echo "<br><br>"; // You know this part... echo "USER NAME: " . $_POST['user-name'] . "<br>"; echo "USER EMAIL: " . $_POST['user-email'] . "<br>"; // This can be a little more confusing for beginners. // $_POST['user-fav'] is now an array of array echo "FAV COLORS: <br>"; foreach ($_POST['user-fav']['color'] as $color) { echo $color . "<br>"; } echo "FAV FOOD: <br>"; foreach ($_POST['user-fav']['food'] as $food) { echo $food . "<br>"; }
AJAX ARRAY POST
마지막으로 Javascript AJAX 호출을 통해 배열을 게시하는 방법을 살펴 보겠습니다.
HTML
<html> <head> <title> AJAX Array Demo </title> <style> /* [DOES NOT MATTER, JUST COSMETICS] */ form { font-family: arial, sans-serif; max-width: 300px; } label, input { display: block; width: 100%; margin: 5px 0; padding: 5px; box-sizing: border-box; } input[type=submit] { background: #305ba0; color: #fff; border: 0; margin-top: 10px; } </style> <script src="4b-form.js"></script> </head> <body> <form onsubmit="return save()"> <label>Name</label> <input type="text" name="user-name" required value="John Doe"/> <label>Email</label> <input type="email" name="user-email" required value="john@doe.com"/> <label>Address</label> <input type="text" name="user-addr[]" required value="Foo Street 123"/> <input type="text" name="user-addr[]" required value="Hello World 345"/> <label>Favorite Colors</label> <input type="text" name="user-fav[color][]" required value="red"/> <input type="text" name="user-fav[color][]" required value="green"/> <input type="text" name="user-fav[color][]"/> <label>Favorite Food</label> <input type="text" name="user-fav[food][]" required value="bacon"/> <input type="text" name="user-fav[food][]" required value="eggs"/> <input type="text" name="user-fav[food][]" value=""/> <input type="submit" value="Submit"/> </form> </body> </html>
여기에는 큰 차이가 없습니다. 여전히 동일한 HTML 양식이지만 onsubmit = "return save"를 사용하여 Javascript가 대신 제출을 처리하도록 합니다.
JAVASCRIPT
function save () { // (A) COLLECT FORM DATA var data = new FormData(); // These should be pretty straight forward data.append('user-name', document.getElementsByName("user-name")[0].value); data.append('user-email', document.getElementsByName("user-email")[0].value); // We do pretty much the same in Javascript for array fields // Add a pair of square brackets to the end of the name var fields = document.getElementsByName("user-addr[]"); for (var f of fields) { data.append('user-addr[]', f.value); } // Same for multi-dimensional arrays as well fields = document.getElementsByName("user-fav[color][]"); for (var f of fields) { data.append('user-fav[color][]', f.value); } fields = document.getElementsByName("user-fav[food][]"); for (var f of fields) { data.append('user-fav[food][]', f.value); } // (B) AJAX CALL var xhr = new XMLHttpRequest(); xhr.open('POST', "4c-server.php", true); // When the process is complete xhr.onload = function(){ console.log("Done"); console.log(this.response); alert("OK - See console for server response"); }; // Send xhr.send(data); return false; }
처음에는 초보자에게는 약간 혼란스러워 보일 수 있지만 자세히 살펴보십시오.이 스크립트에는 두 부분 만 있습니다.
SERVER PHP
print_r($_POST);
여기서 볼 것이 없습니다. 제출되는 모든 내용을 반영하는 더미 스크립트입니다.
유용한 비트
이것이 이 프로젝트의 전부이며, 여기에 도움이 될만한 추가 정보에 대한 작은 섹션이 있습니다.
INFOGRAPHICS CHEAT SHEET
참조
등록된 댓글이 없습니다.