所以我试图创建一个简单的ajax请求,从data.txt(在同一个根目录中)返回hello world文本。
问题:检查状态时=== 200 if语句不显示 任何东西,即它没有回归真实。
TWIST:但如果if语句被删除,则会记录请求 控制台(但数据没有写在页面上。
CODE
// AJAX REQUEST EXAMPLE
// XHR is the api that is used for AJAX REQUESTS
// Create a XHR request object
var request = new XMLHttpRequest();
// create the 'request' for this object. open() reqest method GET/POST, location of the data file (ajax requests has same domain poilcy - so you can't request data objects for domains from other than what your currently on), true/fasle (whether we want request ot be asyncronous or not fasle means its asyc i.e. brwoser waits until requests is done before it does anything else )
request.open('GET', 'data.txt', true);
// send request to the server for data
request.send();
if (request.status=== 200) {
document.writeln(request.responseText);
}
console.log(request);
答案 0 :(得分:1)
希望这有助于您理解,我已经为您提供了一些意见。随意问我一切:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>stackoverflow test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
// AJAX REQUEST EXAMPLE
// XHR is the api that is used for AJAX REQUESTS
// Create a XHR request object
var request = new XMLHttpRequest();
request.onreadystatechange = function() //This is to wait for response (eventually from your PHP script)
{
if (request.readyState === 4 && request.status === 200) //And when status is OK use result
{
document.writeln(request.responseText);
console.log(request.status); //here the status request
console.log(request); //here the complete object request
}
}
// open() request method GET/POST, location of the data file (ajax requests has same domain policy - so you can't request data objects for domains from other than what your currently on), true/false (whether we want request ot be asyncronous or not false means its asyc i.e. browser waits until requests is done before it does anything else )
request.open('GET', 'data.txt', true);
// send request to the server for data
request.send();
</script>
</body>
</html>
现在,您将在浏览器控制台中获得200
success request
,并在浏览器中获得data.txt
输出。
干杯,朱利奥
答案 1 :(得分:0)