댓글 검색 목록

[php] Javascript에서 PHP 파일을 호출하는 방법

페이지 정보

작성자 운영자 작성일 20-04-19 17:10 조회 1,102 댓글 0

클라이언트 서버 스크립트 


Javascript에서 PHP 파일을 호출하는 방법에 대한 자습서에 오신 것을 환영합니다. Javascript에서 프로세스를 완료하려면 PHP 파일을 호출해야 합니까? 실제로 Javascript로 PHP 스크립트를 호출하는 몇 가지 방법이 있습니다.

  • AJAX를 사용하여 PHP 스크립트를 호출하십시오.
  • PHP 스크립트에 HTML 양식을 제출하십시오.
  • 현재 페이지를 PHP 스크립트로 리디렉션 하십시오.
  • 마지막으로, PHP 스크립트를 가리키는 스크립트 태그를 동적으로 생성하는 정통적인 방법입니다.

그러나 우리는 어떻게 합니까? 이 안내서의 몇 가지 예를 살펴 보겠습니다. 계속 읽으십시오!


ⓘ이 튜토리얼의 시작 부분에 모든 소스 코드가 포함 된 zip 파일이 포함되어 있으므로 모든 것을 복사하여 붙여 넣을 필요가 없습니다.


소스 코드 다운로드 


먼저 약속 된 다운로드 링크가 있습니다.


소스 코드 다운로드 


소스 코드를 다운로드하려면 여기를 클릭하십시오. MIT 라이센스에 따라 릴리스되었으므로 그 위에 빌드하거나 자신의 프로젝트에서 자유롭게 사용하십시오.


빠른 시작 


  • 폴더에 다운로드하여 압축을 풉니다.
  • 관련된 데이터베이스가 없으므로 포함 된 각 파일을 따라 가십시오.

AJAX CALL 


이것이 권장되는 방법이며, 모르는 분들을 위해 AJAX는 비동기 자바 스크립트 및 XML을 나타냅니다. 전체 페이지를 다시 로드하여 여러 백그라운드 프로세스를 수행 할 수 있기 때문에 오늘날 가장 현대적인 웹 사이트를 구동하는 것입니다.


THE HTML & JAVASCRIPT 


<!DOCTYPE html> <html> <head> <title> Call PHP File via AJAX </title> <script> function ajaxcall() { // GET DATA var data = new FormData(); data.append('name', document.getElementById("user-name").value); data.append('email', document.getElementById("user-email").value); // AJAX CALL var xhr = new XMLHttpRequest(); xhr.open('POST', "1b-ajax.php", true); xhr.onload = function () { var res = JSON.parse(this.response); if (res.status) { // OK - DO SOMETHING alert(res.message); } else { // ERROR - DO SOMETHING alert(res.message); } }; xhr.send(data); return false; } </script> </head> <body> <form onsubmit="return ajaxcall();"> <label for="user-name">Name</label> <input type="text" id="user-name" required/> <label for="user-email">Email</label> <input type="email" id="user-email" required/> <input type="submit" value="Save"/> </form> </body> </html> 


이것은 매우 간단해야 하며 HTML에는 두 부분이 있습니다.


  • 먼저 맨 아래에 일반적인 HTML 양식이 있습니다.
  • 둘째, 양식 제출을 처리하기 위해 Javascript를 사용합니다. 그러나 양식을 직접 제출하는 대신 백그라운드에서 실행될 AJAX 요청을 만듭니다.

PHP 스크립트 

<?php // PHP FUNCTION YOU WANT TO CALL function save ($name, $email) { // Do your processing // Save to database of something return true; } // PUT THE POST VARIABLES IN $pass = save($_POST['name'], $_POST['email']); // RESULT echo json_encode([ "status" => $pass ? 1 : 0, "message" => $pass ? "OK" : "An error has occured" ]); ?> 


이 스크립트는 일반적으로 HTML 양식 POST를 처리하는 방식과 동일하게 작동합니다. 그러나 JSON을 사용하여 처리 방법에 대한 서버 응답의 형식을 지정합니다. 처리가 성공했거나 오류가 발생한 경우에 유의하십시오. 이것은 Javascript의 xhr.onload에 의해 선택됩니다.


양식 제출 


이것은 HTML 양식 제출과 관련된 구식 방법으로 전체 페이지를 다시 로드 해야 하므로 권장하지 않지만 작동합니다.


HTML과 자바 스크립트 


<!DOCTYPE html> <html> <head> <title> Call PHP File via Form Submission </title> </head> <body> <!-- (1) HTML FORM --> <form method="post" action="2b-submit.php" onsubmit="return save();"> <label for="user-name">Name</label> <input type="text" id="user-name" name="name" required/> <label for="user-email">Email</label> <input type="email" id="user-email" name="email" required/> <input type="submit" value="Save"/> </form> <script> // (2) JS FUNCTION function save () { // DO YOUR JS PROCESSING // Maybe add further checks on the input // User name must be at least 4 characters var pass = true; if (document.getElementById("user-name").value.length < 4) { pass = false; alert("User name must be at least 4 characters"); } return pass; } </script> <?php if (@is_array($error)) { // (3) SHOW ERROR - IF ANY echo "<div style='font-weight:bold; color:#e00;'>"; foreach ($error as $e) { echo "<p>$e</p>"; } echo "</div>"; } ?> </body> </html> 



이 스크립트에는 3 가지 부분이 있습니다.

  • 먼저 평소와 같이 HTML 형식을 사용합니다.
  • 다음으로, 점검 및 처리를 수행 할 Javascript입니다.
  • 마지막으로, PHP 처리 후 오류 메시지 (있는 경우)를 표시하는 컨테이너입니다.


PHP 스크립트 


<?php if ($_POST) { // PHP FUNCTION YOU WANT TO CALL function save ($name, $email) { // Do your processing // Save to database of something return false; } // PUT THE POST VARIABLES IN $pass = save($_POST['name'], $_POST['email']); // PROCESS RESULT if ($pass) { // OK - SHOW AN "OK" PAGE OR SOMETHING // require "ok.html"; echo "OK"; } else { // ERROR $error = [ "Testing", "Foo bar!" ]; require "2a-form.php"; } } ?> 


HTML 양식 제출시 사용자 입력이 이 스크립트에 POST됩니다. 필요에 따라 처리 한 다음 그에 따라 결과를 출력하십시오.


방향 전환의 게임 


이것은 또 다른 구식 방법이며, 쿼리 문자열로 데이터를 전달하면서 사용자를 PHP 페이지로 리디렉션 합니다. 권장되지는 않지만 요즘에는 여전히 일반적입니다.


HTML과 자바 스크립트 


<!DOCTYPE html> <html> <head> <title> Redirection with Query String </title> </head> <body> <!-- (1) HTML FORM --> <form onsubmit="return redr();"> <label for="no-1">First Number</label> <input type="number" id="no-1" required/> <label for="no-2">Second Number</label> <input type="number" id="no-2" required/> <input type="submit" value="Add"/> </form> <!-- (2) JAVASCRIPT --> <script> function redr () { // Append the JS variables as query string var src = "3b-redirect.php"; src += "?first=" + document.getElementById("no-1").value; src += "&second=" + document.getElementById("no-2").value; // Redirection window.location.href = src; return false; } </script> <!-- (3) RESULT --> <?php if (@is_numeric($total)) { echo "<strong>TOTAL SUM IS $total</strong>"; } ?> </body> </html> 


이것은 HTML 양식 제출과 매우 유사합니다. 맨 위의 선택적 양식, 리디렉션 URL 및 쿼리 문자열을 공식화하는 Javascript 및 프로세스 결과입니다.


PHP 


<?php // PHP FUNCTION YOU WANT TO CALL function add ($first, $second) { return $first + $second; } // PUT THE VARIABLES IN $total = add($_GET['first'], $_GET['second']); // RESULT require "3a-redirect.php"; 


이것은 설명이 필요합니다.


정통 방법 


글쎄요,이 마지막 예제는 나쁜 것입니다. 그것은 일종의 효과가 있지만, 이것을 하지 않는 방법입니다.


HTML과 자바 스크립트 


<!DOCTYPE html> <html> <head> <title> Unorthodox Way - Dynamic Javascript </title> </head> <body> <!-- (1) HTML FORM --> <form onsubmit="return badway();"> <label for="no-1">First Number</label> <input type="number" id="no-1" required/> <label for="no-2">Second Number</label> <input type="number" id="no-2" required/> <input type="submit" value="Add"/> </form> <!-- (2) ILLEGAL DUMPING GROUND --> <div id="dumping-ground"></div> <!-- (3) JAVASCRIPT --> <script> function badway () { // Dynamically create a new script and inject. // Not a good way, and not recommended var tag = document.createElement("script"); // Append the JS variables as query string var src = "4b-unorthodox.php"; src += "?first=" + document.getElementById("no-1").value; src += "&second=" + document.getElementById("no-2").value; tag.src = src; // Put the "Javascript" into the dumping ground so that it loads and runs var dump = document.getElementById("dumping-ground"); dump.appendChild(tag); dump.removeChild(tag); return false; } </script> </body> </html> 


PHP 


<?php // PHP FUNCTION YOU WANT TO CALL function add ($first, $second) { return $first + $second; } // PUT THE GET VARIABLES IN $total = add($_GET['first'], $_GET['second']); // NOW WEAVING BACK TO JAVASCRIPT ?> alert(<?=$total?>); 


이 방법에서 발생하는 일은 매우 로터리입니다.


  • HTML 양식에서 사용자 입력을 얻습니다.
  • 새 스크립트 태그를 작성하여 PHP 파일을 가리키고 쿼리 문자열에 사용자 입력을 추가하십시오.
  • 평소와 같이 PHP를 처리 한 다음 Javascript를 출력하도록 엮습니다.

네, 그냥 AJAX를 사용하십시오…


유용한 비트 


이것이 이 프로젝트의 전부이며, 여기에 도움이 될만한 추가 정보에 대한 작은 섹션이 있습니다.



댓글목록 0

등록된 댓글이 없습니다.

웹학교 로고

온라인 코딩학교

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