本文用实际例子说明如何发送 Ajax 请求给后台PHP服务,并获取后台 php 的响应内容。
以下示例显示了网页如何与 web 服务器通信并获取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");
?>以下示例显示了在用户在输入字段中键入字符时网页如何与Web服务器通信:
在下面的输入字段中开始输入国家/地区名称:
国家:
意见建议:
在上面的示例中,当用户在输入字段中键入字符时,事件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;
?>