例子
代码
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);
也就是异步改为同步,就可以得到返回值
本文探讨了JavaScript中的Ajax异步请求问题。在默认情况下,Ajax请求是异步的,导致在console.log中无法立即获取到响应内容。为解决此问题,可以将xhr.open的第三个参数设置为false,使请求变为同步,从而确保在控制台能正确输出PHP文件返回的'hellohellohello'。然而,同步请求会阻塞浏览器直到请求完成,可能影响用户体验。因此,在实际开发中需权衡异步与同步的使用场景。
1459

被折叠的 条评论
为什么被折叠?



