本文用實(shí)際例子說(shuō)明如何發(fā)送 Ajax 請(qǐng)求給后臺(tái)PHP服務(wù),并獲取后臺(tái) php 的響應(yīng)內(nèi)容。
以下示例顯示了網(wǎng)頁(yè)如何與 web 服務(wù)器通信并獲取PHP的執(zhí)行結(jié)果:
在上面的示例中,事件fetchDoc()執(zhí)行了一個(gè)函數(shù)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"); ?>
以下示例顯示了在用戶在輸入字段中鍵入字符時(shí)網(wǎng)頁(yè)如何與Web服務(wù)器通信:
在下面的輸入字段中開始輸入國(guó)家/地區(qū)名稱:
國(guó)家:
意見建議:
在上面的示例中,當(dāng)用戶在輸入字段中鍵入字符時(shí),事件showHint()將執(zhí)行功能onkeyup。
這是HTML代碼:
<!DOCTYPE html> <html> <div> <p>在下面的輸入字段中開始輸入國(guó)家/地區(qū)名稱:</p> <p>國(guó)家: <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 // 國(guó)家名數(shù)組 $countries = array("Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra",...); // 從URL獲取q參數(shù) $q = $_REQUEST["q"]; $hint = ""; // 如果$q與數(shù)組中的提示不同,則循環(huán)遍歷數(shù)組中的所有提示 "" 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"; } } } } //如果沒(méi)有發(fā)現(xiàn)提示或輸出正確的值,則輸出“no suggestion” echo $hint === "" ? "no suggestion" : $hint; ?>