AJAX:request.status == 200返回false? (数据未显示在页面上)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AJAX:request.status == 200返回false? (数据未显示在页面上)相关的知识,希望对你有一定的参考价值。
所以我试图创建一个简单的ajax请求,从data.txt(在同一个根目录中)返回hello world文本。
问题:当检查状态时=== 200 if语句没有显示任何内容,即它没有返回true。
TWIST:但是如果if语句被删除,请求将被记录到控制台上(但是数据没有写在页面上。
码
// 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);
答案
希望这有助于您理解,我已经为您提出了一些意见。随意问我一切:
<!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
。
干杯,朱利奥
另一答案
200意味着成功
以上是关于AJAX:request.status == 200返回false? (数据未显示在页面上)的主要内容,如果未能解决你的问题,请参考以下文章