English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
이 장에서는 AJAX 요청을 PHP 파일로 보내고 PHP 파일의 내용을检索하는 방법을 설명하겠습니다.
다음 예제는 웹 페이지가 네트워크 서버와 통신하여 PHP 파일의 내용을检索하는 방법을 보여줍니다:
위의 예제에서 이벤트 fetchDoc()가 onclick 함수를 실행합니다.
이는 HTML 코드입니다:
<button type="button" onclick="fetchDoc()">Fetch Content</button> <div id="output"></div> <script> function fetchDoc() { var httpRequest = new XMLHttpRequest(); httpRequest.onreadystatechange = function() { if (this.readyState === 4 && this.status === 200) { document.getElementById("output").innerHTML = this.responseText; } }; httpRequest.open("GET", "ajax_time.php", true); httpRequest.send(); } </script>
이는 PHP 코드입니다 (ajax_time.php):
<?php echo date("d/m/Y, h:i:s A"); ?>
다음 예제는 사용자가 입력 필드에서 문자를 입력할 때 웹 페이지가 웹 서버와 어떻게 통신하는지 보여줍니다:
아래 입력 필드에서 국가를 시작으로 입력하세요/지역 이름:
국가:
의견 및 제안:
위의 예제에서 사용자가 입력 필드에서 문자를 입력할 때, 이벤트 showHint()가 onkeyup 기능을 실행합니다.
이는 HTML 코드입니다:
<!DOCTYPE html> <html> <div> <p>아래 입력 필드에서 국가를 시작으로 입력하세요/지역 이름:/p> <p>국가: <input type="text" onkeyup="showHint(this.value)"></p> <p>추천: <span id="result"></span></p> </div> <script> var elem = document.getElementById("result"); function showHint(name) { if (name.length === 0) {}} elem.innerHTML = ""; return; } else { var httpRequest = new XMLHttpRequest(); httpRequest.onreadystatechange = function() { if (this.readyState === 4 && this.status === 200) { elem.innerHTML = this.responseText; } }; httpRequest.open("GET", "ajax_hint.php?q=" + name, true); httpRequest.send(); } } </script> </html>
이것은 PHP 코드입니다 (ajax_hint.php):
<?php // 국가 이름 배열 $countries = array("Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra",...); // URL에서 q 파라미터를 가져옵니다 $q = $_REQUEST["q"]; $hint = ""; // 如果$q与数组中的提示不同,则循环遍历数组中的所有提示 "" if ($q !== "") { $q = strtolower($q); $len = strlen($q); foreach($countries as $name) { if (stristr($q, substr($name, 0, $len))) { if ($hint === "") { $hint = $name; } else { $hint .= ", $name"; } } } } //ヒント이 발견되지 않거나 올바른 값을 출력하면 "no suggestion"을 출력합니다 echo $hint === "" ? "no suggestion" : $hint; ?>
국가 이름의 완전한 목록은 다음을 참조하십시오https://gist.github.com/DHS/1340150