PHP 总是在 JavaScript 之前工作,所以让 JavaScript 让 PHP 再次运行的唯一方法是启动另一个请求。XMLHttpRequest
JavaScript 可以通过使用通常称为 AJAX的方式启动请求而无需转到新页面。JavaScript 代码看起来像这样:
// For old versions of Internet Explorer, you need to catch if this fails and use
// ActiveXObject to create an XMLHttpRequest.
var xhr = new XMLHttpRequest();
xhr.open("GET" /* or POST if it's more suitable */, "some/url.php", true);
xhr.send(null); // replace null with POST data, if any
这样就可以发送请求,但您可能也想获取结果数据。为此,您必须设置一个回调(可能在您调用之前send
):
xhr.onreadystatechange = function() {
// This function will be called whenever the state of the XHR object changes.
// When readyState is 4, it has finished loading, and that's all we care
// about.
if(xhr.readyState === 4) {
// Make sure there wasn't an HTTP error.
if(xhr.status >= 200 && xhr.status < 300) {
// It was retrieved successfully. Alert the result.
alert(xhr.responseText);
}else{
// There was an error.
alert("Oh darn, an error occurred.");
}
}
};
需要注意的一点是,send
仅启动请求;它不会等到它完成。有时您必须重组代码以适应这种情况。