我想在点击按钮时触发AJAX请求,但我无法在后端触发它。
index.php:
<html>
<head>
<script type="text/javascript">
var req = new XMLHttpRequest();
function send1()
{
req.open("GET", "process.php?q=hello", true);
req.send();
alert(req.responseText);
}
</script>
</head>
<button onclick=send1()>send</button>
</html>
process.php:
<?php
$new= $_GET['q'];
echo $new;
?>
这应该会在警报框中给我"你好",为什么不是呢?
AJAX中的第一个A表示"异步"。你需要做的是倾听readyState的变化:
req.open(...);
req.onreadystatechange = function() {
if( this.readyState == 4) {
if( this.status == 200) alert(this.responseText);
else alert("HTTP error "+this.status+" "+this.statusText);
}
};
req.send();