例子
代码
js:
let str = '';
let xhr = new XMLHttpRequest();
// 监听ajax的状态
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
str = xhr.response;
}
}
xhr.open('get', './test.php');
xhr.send();
console.log('str', str);//结果:不能输出test.php中内容
php:
<?php
echo "hellohellohello";
?>
结果
str没有值,也就是说没有获得xhr.response的响应信息
因为默认是异步的,此时响应信息还没有返回
解决
把xhr.open的第三个参数从true(不写默认true)改成false,xhr.open('get', './test.php',false);
也就是异步改为同步,就可以得到返回值